three.js 868 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '74dev' };
  6. //
  7. if ( typeof define === 'function' && define.amd ) {
  8. define( 'three', THREE );
  9. } else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) {
  10. module.exports = THREE;
  11. }
  12. // polyfills
  13. if ( self.requestAnimationFrame === undefined || self.cancelAnimationFrame === undefined ) {
  14. // Missing in Android stock browser.
  15. ( function () {
  16. var lastTime = 0;
  17. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  18. for ( var x = 0; x < vendors.length && ! self.requestAnimationFrame; ++ x ) {
  19. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  20. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  21. }
  22. if ( self.requestAnimationFrame === undefined && self.setTimeout !== undefined ) {
  23. self.requestAnimationFrame = function ( callback ) {
  24. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  25. var id = self.setTimeout( function () {
  26. callback( currTime + timeToCall );
  27. }, timeToCall );
  28. lastTime = currTime + timeToCall;
  29. return id;
  30. };
  31. }
  32. if ( self.cancelAnimationFrame === undefined && self.clearTimeout !== undefined ) {
  33. self.cancelAnimationFrame = function ( id ) {
  34. self.clearTimeout( id );
  35. };
  36. }
  37. } )();
  38. }
  39. //
  40. if ( self.performance === undefined ) {
  41. self.performance = {};
  42. }
  43. if ( self.performance.now === undefined ) {
  44. ( function () {
  45. var start = Date.now();
  46. self.performance.now = function () {
  47. return Date.now() - start;
  48. }
  49. } )();
  50. }
  51. //
  52. if ( Number.EPSILON === undefined ) {
  53. Number.EPSILON = Math.pow( 2, -52 );
  54. }
  55. //
  56. if ( Math.sign === undefined ) {
  57. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  58. Math.sign = function ( x ) {
  59. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  60. };
  61. }
  62. if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) {
  63. // Missing in IE9-11.
  64. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  65. Object.defineProperty( Function.prototype, 'name', {
  66. get: function () {
  67. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  68. }
  69. } );
  70. }
  71. if ( Object.assign === undefined ) {
  72. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  73. Object.defineProperty( Object, 'assign', {
  74. writable: true,
  75. configurable: true,
  76. value: function(target) {
  77. 'use strict';
  78. if ( target === undefined || target === null ) {
  79. throw new TypeError( "Cannot convert first argument to object" );
  80. }
  81. var to = Object( target );
  82. for ( var i = 1, n = arguments.length; i !== n; ++ i ) {
  83. var nextSource = arguments[ i ];
  84. if ( nextSource === undefined || nextSource === null ) continue;
  85. nextSource = Object( nextSource );
  86. var keysArray = Object.keys( nextSource );
  87. for ( var nextIndex = 0, len = keysArray.length; nextIndex !== len; ++ nextIndex ) {
  88. var nextKey = keysArray[ nextIndex ];
  89. var desc = Object.getOwnPropertyDescriptor( nextSource, nextKey );
  90. if ( desc !== undefined && desc.enumerable ) {
  91. to[ nextKey ] = nextSource[ nextKey ];
  92. }
  93. }
  94. }
  95. return to;
  96. }
  97. } );
  98. }
  99. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  100. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  101. // GL STATE CONSTANTS
  102. THREE.CullFaceNone = 0;
  103. THREE.CullFaceBack = 1;
  104. THREE.CullFaceFront = 2;
  105. THREE.CullFaceFrontBack = 3;
  106. THREE.FrontFaceDirectionCW = 0;
  107. THREE.FrontFaceDirectionCCW = 1;
  108. // SHADOWING TYPES
  109. THREE.BasicShadowMap = 0;
  110. THREE.PCFShadowMap = 1;
  111. THREE.PCFSoftShadowMap = 2;
  112. // MATERIAL CONSTANTS
  113. // side
  114. THREE.FrontSide = 0;
  115. THREE.BackSide = 1;
  116. THREE.DoubleSide = 2;
  117. // shading
  118. THREE.FlatShading = 1;
  119. THREE.SmoothShading = 2;
  120. // colors
  121. THREE.NoColors = 0;
  122. THREE.FaceColors = 1;
  123. THREE.VertexColors = 2;
  124. // blending modes
  125. THREE.NoBlending = 0;
  126. THREE.NormalBlending = 1;
  127. THREE.AdditiveBlending = 2;
  128. THREE.SubtractiveBlending = 3;
  129. THREE.MultiplyBlending = 4;
  130. THREE.CustomBlending = 5;
  131. // custom blending equations
  132. // (numbers start from 100 not to clash with other
  133. // mappings to OpenGL constants defined in Texture.js)
  134. THREE.AddEquation = 100;
  135. THREE.SubtractEquation = 101;
  136. THREE.ReverseSubtractEquation = 102;
  137. THREE.MinEquation = 103;
  138. THREE.MaxEquation = 104;
  139. // custom blending destination factors
  140. THREE.ZeroFactor = 200;
  141. THREE.OneFactor = 201;
  142. THREE.SrcColorFactor = 202;
  143. THREE.OneMinusSrcColorFactor = 203;
  144. THREE.SrcAlphaFactor = 204;
  145. THREE.OneMinusSrcAlphaFactor = 205;
  146. THREE.DstAlphaFactor = 206;
  147. THREE.OneMinusDstAlphaFactor = 207;
  148. // custom blending source factors
  149. //THREE.ZeroFactor = 200;
  150. //THREE.OneFactor = 201;
  151. //THREE.SrcAlphaFactor = 204;
  152. //THREE.OneMinusSrcAlphaFactor = 205;
  153. //THREE.DstAlphaFactor = 206;
  154. //THREE.OneMinusDstAlphaFactor = 207;
  155. THREE.DstColorFactor = 208;
  156. THREE.OneMinusDstColorFactor = 209;
  157. THREE.SrcAlphaSaturateFactor = 210;
  158. // depth modes
  159. THREE.NeverDepth = 0;
  160. THREE.AlwaysDepth = 1;
  161. THREE.LessDepth = 2;
  162. THREE.LessEqualDepth = 3;
  163. THREE.EqualDepth = 4;
  164. THREE.GreaterEqualDepth = 5;
  165. THREE.GreaterDepth = 6;
  166. THREE.NotEqualDepth = 7;
  167. // TEXTURE CONSTANTS
  168. THREE.MultiplyOperation = 0;
  169. THREE.MixOperation = 1;
  170. THREE.AddOperation = 2;
  171. // Mapping modes
  172. THREE.UVMapping = 300;
  173. THREE.CubeReflectionMapping = 301;
  174. THREE.CubeRefractionMapping = 302;
  175. THREE.EquirectangularReflectionMapping = 303;
  176. THREE.EquirectangularRefractionMapping = 304;
  177. THREE.SphericalReflectionMapping = 305;
  178. // Wrapping modes
  179. THREE.RepeatWrapping = 1000;
  180. THREE.ClampToEdgeWrapping = 1001;
  181. THREE.MirroredRepeatWrapping = 1002;
  182. // Filters
  183. THREE.NearestFilter = 1003;
  184. THREE.NearestMipMapNearestFilter = 1004;
  185. THREE.NearestMipMapLinearFilter = 1005;
  186. THREE.LinearFilter = 1006;
  187. THREE.LinearMipMapNearestFilter = 1007;
  188. THREE.LinearMipMapLinearFilter = 1008;
  189. // Data types
  190. THREE.UnsignedByteType = 1009;
  191. THREE.ByteType = 1010;
  192. THREE.ShortType = 1011;
  193. THREE.UnsignedShortType = 1012;
  194. THREE.IntType = 1013;
  195. THREE.UnsignedIntType = 1014;
  196. THREE.FloatType = 1015;
  197. THREE.HalfFloatType = 1025;
  198. // Pixel types
  199. //THREE.UnsignedByteType = 1009;
  200. THREE.UnsignedShort4444Type = 1016;
  201. THREE.UnsignedShort5551Type = 1017;
  202. THREE.UnsignedShort565Type = 1018;
  203. // Pixel formats
  204. THREE.AlphaFormat = 1019;
  205. THREE.RGBFormat = 1020;
  206. THREE.RGBAFormat = 1021;
  207. THREE.LuminanceFormat = 1022;
  208. THREE.LuminanceAlphaFormat = 1023;
  209. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  210. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  211. // DDS / ST3C Compressed texture formats
  212. THREE.RGB_S3TC_DXT1_Format = 2001;
  213. THREE.RGBA_S3TC_DXT1_Format = 2002;
  214. THREE.RGBA_S3TC_DXT3_Format = 2003;
  215. THREE.RGBA_S3TC_DXT5_Format = 2004;
  216. // PVRTC compressed texture formats
  217. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  218. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  219. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  220. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  221. // Loop styles for AnimationAction
  222. THREE.LoopOnce = 2200;
  223. THREE.LoopRepeat = 2201;
  224. THREE.LoopPingPong = 2202;
  225. // Interpolation
  226. THREE.InterpolateDiscrete = 2300;
  227. THREE.InterpolateLinear = 2301;
  228. THREE.InterpolateSmooth = 2302;
  229. // Interpolant ending modes
  230. THREE.ZeroCurvatureEnding = 2400;
  231. THREE.ZeroSlopeEnding = 2401;
  232. THREE.WrapAroundEnding = 2402;
  233. // Triangle Draw modes
  234. THREE.TrianglesDrawMode = 0;
  235. THREE.TriangleStripDrawMode = 1;
  236. THREE.TriangleFanDrawMode = 2;
  237. // File:src/math/Color.js
  238. /**
  239. * @author mrdoob / http://mrdoob.com/
  240. */
  241. THREE.Color = function ( color ) {
  242. if ( arguments.length === 3 ) {
  243. return this.fromArray( arguments );
  244. }
  245. return this.set( color );
  246. };
  247. THREE.Color.prototype = {
  248. constructor: THREE.Color,
  249. r: 1, g: 1, b: 1,
  250. set: function ( value ) {
  251. if ( value instanceof THREE.Color ) {
  252. this.copy( value );
  253. } else if ( typeof value === 'number' ) {
  254. this.setHex( value );
  255. } else if ( typeof value === 'string' ) {
  256. this.setStyle( value );
  257. }
  258. return this;
  259. },
  260. setHex: function ( hex ) {
  261. hex = Math.floor( hex );
  262. this.r = ( hex >> 16 & 255 ) / 255;
  263. this.g = ( hex >> 8 & 255 ) / 255;
  264. this.b = ( hex & 255 ) / 255;
  265. return this;
  266. },
  267. setRGB: function ( r, g, b ) {
  268. this.r = r;
  269. this.g = g;
  270. this.b = b;
  271. return this;
  272. },
  273. setHSL: function () {
  274. function hue2rgb( p, q, t ) {
  275. if ( t < 0 ) t += 1;
  276. if ( t > 1 ) t -= 1;
  277. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  278. if ( t < 1 / 2 ) return q;
  279. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  280. return p;
  281. }
  282. return function ( h, s, l ) {
  283. // h,s,l ranges are in 0.0 - 1.0
  284. h = THREE.Math.euclideanModulo( h, 1 );
  285. s = THREE.Math.clamp( s, 0, 1 );
  286. l = THREE.Math.clamp( l, 0, 1 );
  287. if ( s === 0 ) {
  288. this.r = this.g = this.b = l;
  289. } else {
  290. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  291. var q = ( 2 * l ) - p;
  292. this.r = hue2rgb( q, p, h + 1 / 3 );
  293. this.g = hue2rgb( q, p, h );
  294. this.b = hue2rgb( q, p, h - 1 / 3 );
  295. }
  296. return this;
  297. };
  298. }(),
  299. setStyle: function ( style ) {
  300. function handleAlpha( string ) {
  301. if ( string === undefined ) return;
  302. if ( parseFloat( string ) < 1 ) {
  303. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  304. }
  305. }
  306. var m;
  307. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  308. // rgb / hsl
  309. var color;
  310. var name = m[ 1 ];
  311. var components = m[ 2 ];
  312. switch ( name ) {
  313. case 'rgb':
  314. case 'rgba':
  315. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  316. // rgb(255,0,0) rgba(255,0,0,0.5)
  317. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  318. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  319. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  320. handleAlpha( color[ 5 ] );
  321. return this;
  322. }
  323. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  324. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  325. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  326. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  327. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  328. handleAlpha( color[ 5 ] );
  329. return this;
  330. }
  331. break;
  332. case 'hsl':
  333. case 'hsla':
  334. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  335. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  336. var h = parseFloat( color[ 1 ] ) / 360;
  337. var s = parseInt( color[ 2 ], 10 ) / 100;
  338. var l = parseInt( color[ 3 ], 10 ) / 100;
  339. handleAlpha( color[ 5 ] );
  340. return this.setHSL( h, s, l );
  341. }
  342. break;
  343. }
  344. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  345. // hex color
  346. var hex = m[ 1 ];
  347. var size = hex.length;
  348. if ( size === 3 ) {
  349. // #ff0
  350. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  351. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  352. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  353. return this;
  354. } else if ( size === 6 ) {
  355. // #ff0000
  356. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  357. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  358. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  359. return this;
  360. }
  361. }
  362. if ( style && style.length > 0 ) {
  363. // color keywords
  364. var hex = THREE.ColorKeywords[ style ];
  365. if ( hex !== undefined ) {
  366. // red
  367. this.setHex( hex );
  368. } else {
  369. // unknown color
  370. console.warn( 'THREE.Color: Unknown color ' + style );
  371. }
  372. }
  373. return this;
  374. },
  375. clone: function () {
  376. return new this.constructor( this.r, this.g, this.b );
  377. },
  378. copy: function ( color ) {
  379. this.r = color.r;
  380. this.g = color.g;
  381. this.b = color.b;
  382. return this;
  383. },
  384. copyGammaToLinear: function ( color, gammaFactor ) {
  385. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  386. this.r = Math.pow( color.r, gammaFactor );
  387. this.g = Math.pow( color.g, gammaFactor );
  388. this.b = Math.pow( color.b, gammaFactor );
  389. return this;
  390. },
  391. copyLinearToGamma: function ( color, gammaFactor ) {
  392. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  393. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  394. this.r = Math.pow( color.r, safeInverse );
  395. this.g = Math.pow( color.g, safeInverse );
  396. this.b = Math.pow( color.b, safeInverse );
  397. return this;
  398. },
  399. convertGammaToLinear: function () {
  400. var r = this.r, g = this.g, b = this.b;
  401. this.r = r * r;
  402. this.g = g * g;
  403. this.b = b * b;
  404. return this;
  405. },
  406. convertLinearToGamma: function () {
  407. this.r = Math.sqrt( this.r );
  408. this.g = Math.sqrt( this.g );
  409. this.b = Math.sqrt( this.b );
  410. return this;
  411. },
  412. getHex: function () {
  413. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  414. },
  415. getHexString: function () {
  416. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  417. },
  418. getHSL: function ( optionalTarget ) {
  419. // h,s,l ranges are in 0.0 - 1.0
  420. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  421. var r = this.r, g = this.g, b = this.b;
  422. var max = Math.max( r, g, b );
  423. var min = Math.min( r, g, b );
  424. var hue, saturation;
  425. var lightness = ( min + max ) / 2.0;
  426. if ( min === max ) {
  427. hue = 0;
  428. saturation = 0;
  429. } else {
  430. var delta = max - min;
  431. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  432. switch ( max ) {
  433. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  434. case g: hue = ( b - r ) / delta + 2; break;
  435. case b: hue = ( r - g ) / delta + 4; break;
  436. }
  437. hue /= 6;
  438. }
  439. hsl.h = hue;
  440. hsl.s = saturation;
  441. hsl.l = lightness;
  442. return hsl;
  443. },
  444. getStyle: function () {
  445. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  446. },
  447. offsetHSL: function ( h, s, l ) {
  448. var hsl = this.getHSL();
  449. hsl.h += h; hsl.s += s; hsl.l += l;
  450. this.setHSL( hsl.h, hsl.s, hsl.l );
  451. return this;
  452. },
  453. add: function ( color ) {
  454. this.r += color.r;
  455. this.g += color.g;
  456. this.b += color.b;
  457. return this;
  458. },
  459. addColors: function ( color1, color2 ) {
  460. this.r = color1.r + color2.r;
  461. this.g = color1.g + color2.g;
  462. this.b = color1.b + color2.b;
  463. return this;
  464. },
  465. addScalar: function ( s ) {
  466. this.r += s;
  467. this.g += s;
  468. this.b += s;
  469. return this;
  470. },
  471. multiply: function ( color ) {
  472. this.r *= color.r;
  473. this.g *= color.g;
  474. this.b *= color.b;
  475. return this;
  476. },
  477. multiplyScalar: function ( s ) {
  478. this.r *= s;
  479. this.g *= s;
  480. this.b *= s;
  481. return this;
  482. },
  483. lerp: function ( color, alpha ) {
  484. this.r += ( color.r - this.r ) * alpha;
  485. this.g += ( color.g - this.g ) * alpha;
  486. this.b += ( color.b - this.b ) * alpha;
  487. return this;
  488. },
  489. equals: function ( c ) {
  490. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  491. },
  492. fromArray: function ( array, offset ) {
  493. if ( offset === undefined ) offset = 0;
  494. this.r = array[ offset ];
  495. this.g = array[ offset + 1 ];
  496. this.b = array[ offset + 2 ];
  497. return this;
  498. },
  499. toArray: function ( array, offset ) {
  500. if ( array === undefined ) array = [];
  501. if ( offset === undefined ) offset = 0;
  502. array[ offset ] = this.r;
  503. array[ offset + 1 ] = this.g;
  504. array[ offset + 2 ] = this.b;
  505. return array;
  506. }
  507. };
  508. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  509. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  510. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  511. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  512. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  513. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  514. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  515. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  516. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  517. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  518. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  519. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  520. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  521. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  522. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  523. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  524. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  525. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  526. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  527. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  528. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  529. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  530. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  531. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  532. // File:src/math/Quaternion.js
  533. /**
  534. * @author mikael emtinger / http://gomo.se/
  535. * @author alteredq / http://alteredqualia.com/
  536. * @author WestLangley / http://github.com/WestLangley
  537. * @author bhouston / http://clara.io
  538. */
  539. THREE.Quaternion = function ( x, y, z, w ) {
  540. this._x = x || 0;
  541. this._y = y || 0;
  542. this._z = z || 0;
  543. this._w = ( w !== undefined ) ? w : 1;
  544. };
  545. THREE.Quaternion.prototype = {
  546. constructor: THREE.Quaternion,
  547. get x () {
  548. return this._x;
  549. },
  550. set x ( value ) {
  551. this._x = value;
  552. this.onChangeCallback();
  553. },
  554. get y () {
  555. return this._y;
  556. },
  557. set y ( value ) {
  558. this._y = value;
  559. this.onChangeCallback();
  560. },
  561. get z () {
  562. return this._z;
  563. },
  564. set z ( value ) {
  565. this._z = value;
  566. this.onChangeCallback();
  567. },
  568. get w () {
  569. return this._w;
  570. },
  571. set w ( value ) {
  572. this._w = value;
  573. this.onChangeCallback();
  574. },
  575. set: function ( x, y, z, w ) {
  576. this._x = x;
  577. this._y = y;
  578. this._z = z;
  579. this._w = w;
  580. this.onChangeCallback();
  581. return this;
  582. },
  583. clone: function () {
  584. return new this.constructor( this._x, this._y, this._z, this._w );
  585. },
  586. copy: function ( quaternion ) {
  587. this._x = quaternion.x;
  588. this._y = quaternion.y;
  589. this._z = quaternion.z;
  590. this._w = quaternion.w;
  591. this.onChangeCallback();
  592. return this;
  593. },
  594. setFromEuler: function ( euler, update ) {
  595. if ( euler instanceof THREE.Euler === false ) {
  596. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  597. }
  598. // http://www.mathworks.com/matlabcentral/fileexchange/
  599. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  600. // content/SpinCalc.m
  601. var c1 = Math.cos( euler._x / 2 );
  602. var c2 = Math.cos( euler._y / 2 );
  603. var c3 = Math.cos( euler._z / 2 );
  604. var s1 = Math.sin( euler._x / 2 );
  605. var s2 = Math.sin( euler._y / 2 );
  606. var s3 = Math.sin( euler._z / 2 );
  607. var order = euler.order;
  608. if ( order === 'XYZ' ) {
  609. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  610. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  611. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  612. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  613. } else if ( order === 'YXZ' ) {
  614. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  615. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  616. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  617. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  618. } else if ( order === 'ZXY' ) {
  619. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  620. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  621. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  622. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  623. } else if ( order === 'ZYX' ) {
  624. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  625. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  626. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  627. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  628. } else if ( order === 'YZX' ) {
  629. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  630. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  631. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  632. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  633. } else if ( order === 'XZY' ) {
  634. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  635. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  636. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  637. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  638. }
  639. if ( update !== false ) this.onChangeCallback();
  640. return this;
  641. },
  642. setFromAxisAngle: function ( axis, angle ) {
  643. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  644. // assumes axis is normalized
  645. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  646. this._x = axis.x * s;
  647. this._y = axis.y * s;
  648. this._z = axis.z * s;
  649. this._w = Math.cos( halfAngle );
  650. this.onChangeCallback();
  651. return this;
  652. },
  653. setFromRotationMatrix: function ( m ) {
  654. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  655. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  656. var te = m.elements,
  657. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  658. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  659. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  660. trace = m11 + m22 + m33,
  661. s;
  662. if ( trace > 0 ) {
  663. s = 0.5 / Math.sqrt( trace + 1.0 );
  664. this._w = 0.25 / s;
  665. this._x = ( m32 - m23 ) * s;
  666. this._y = ( m13 - m31 ) * s;
  667. this._z = ( m21 - m12 ) * s;
  668. } else if ( m11 > m22 && m11 > m33 ) {
  669. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  670. this._w = ( m32 - m23 ) / s;
  671. this._x = 0.25 * s;
  672. this._y = ( m12 + m21 ) / s;
  673. this._z = ( m13 + m31 ) / s;
  674. } else if ( m22 > m33 ) {
  675. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  676. this._w = ( m13 - m31 ) / s;
  677. this._x = ( m12 + m21 ) / s;
  678. this._y = 0.25 * s;
  679. this._z = ( m23 + m32 ) / s;
  680. } else {
  681. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  682. this._w = ( m21 - m12 ) / s;
  683. this._x = ( m13 + m31 ) / s;
  684. this._y = ( m23 + m32 ) / s;
  685. this._z = 0.25 * s;
  686. }
  687. this.onChangeCallback();
  688. return this;
  689. },
  690. setFromUnitVectors: function () {
  691. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  692. // assumes direction vectors vFrom and vTo are normalized
  693. var v1, r;
  694. var EPS = 0.000001;
  695. return function ( vFrom, vTo ) {
  696. if ( v1 === undefined ) v1 = new THREE.Vector3();
  697. r = vFrom.dot( vTo ) + 1;
  698. if ( r < EPS ) {
  699. r = 0;
  700. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  701. v1.set( - vFrom.y, vFrom.x, 0 );
  702. } else {
  703. v1.set( 0, - vFrom.z, vFrom.y );
  704. }
  705. } else {
  706. v1.crossVectors( vFrom, vTo );
  707. }
  708. this._x = v1.x;
  709. this._y = v1.y;
  710. this._z = v1.z;
  711. this._w = r;
  712. this.normalize();
  713. return this;
  714. }
  715. }(),
  716. inverse: function () {
  717. this.conjugate().normalize();
  718. return this;
  719. },
  720. conjugate: function () {
  721. this._x *= - 1;
  722. this._y *= - 1;
  723. this._z *= - 1;
  724. this.onChangeCallback();
  725. return this;
  726. },
  727. dot: function ( v ) {
  728. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  729. },
  730. lengthSq: function () {
  731. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  732. },
  733. length: function () {
  734. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  735. },
  736. normalize: function () {
  737. var l = this.length();
  738. if ( l === 0 ) {
  739. this._x = 0;
  740. this._y = 0;
  741. this._z = 0;
  742. this._w = 1;
  743. } else {
  744. l = 1 / l;
  745. this._x = this._x * l;
  746. this._y = this._y * l;
  747. this._z = this._z * l;
  748. this._w = this._w * l;
  749. }
  750. this.onChangeCallback();
  751. return this;
  752. },
  753. multiply: function ( q, p ) {
  754. if ( p !== undefined ) {
  755. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  756. return this.multiplyQuaternions( q, p );
  757. }
  758. return this.multiplyQuaternions( this, q );
  759. },
  760. multiplyQuaternions: function ( a, b ) {
  761. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  762. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  763. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  764. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  765. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  766. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  767. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  768. this.onChangeCallback();
  769. return this;
  770. },
  771. slerp: function ( qb, t ) {
  772. if ( t === 0 ) return this;
  773. if ( t === 1 ) return this.copy( qb );
  774. var x = this._x, y = this._y, z = this._z, w = this._w;
  775. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  776. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  777. if ( cosHalfTheta < 0 ) {
  778. this._w = - qb._w;
  779. this._x = - qb._x;
  780. this._y = - qb._y;
  781. this._z = - qb._z;
  782. cosHalfTheta = - cosHalfTheta;
  783. } else {
  784. this.copy( qb );
  785. }
  786. if ( cosHalfTheta >= 1.0 ) {
  787. this._w = w;
  788. this._x = x;
  789. this._y = y;
  790. this._z = z;
  791. return this;
  792. }
  793. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  794. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  795. this._w = 0.5 * ( w + this._w );
  796. this._x = 0.5 * ( x + this._x );
  797. this._y = 0.5 * ( y + this._y );
  798. this._z = 0.5 * ( z + this._z );
  799. return this;
  800. }
  801. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  802. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  803. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  804. this._w = ( w * ratioA + this._w * ratioB );
  805. this._x = ( x * ratioA + this._x * ratioB );
  806. this._y = ( y * ratioA + this._y * ratioB );
  807. this._z = ( z * ratioA + this._z * ratioB );
  808. this.onChangeCallback();
  809. return this;
  810. },
  811. equals: function ( quaternion ) {
  812. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  813. },
  814. fromArray: function ( array, offset ) {
  815. if ( offset === undefined ) offset = 0;
  816. this._x = array[ offset ];
  817. this._y = array[ offset + 1 ];
  818. this._z = array[ offset + 2 ];
  819. this._w = array[ offset + 3 ];
  820. this.onChangeCallback();
  821. return this;
  822. },
  823. toArray: function ( array, offset ) {
  824. if ( array === undefined ) array = [];
  825. if ( offset === undefined ) offset = 0;
  826. array[ offset ] = this._x;
  827. array[ offset + 1 ] = this._y;
  828. array[ offset + 2 ] = this._z;
  829. array[ offset + 3 ] = this._w;
  830. return array;
  831. },
  832. onChange: function ( callback ) {
  833. this.onChangeCallback = callback;
  834. return this;
  835. },
  836. onChangeCallback: function () {}
  837. };
  838. Object.assign( THREE.Quaternion, {
  839. slerp: function( qa, qb, qm, t ) {
  840. return qm.copy( qa ).slerp( qb, t );
  841. },
  842. slerpFlat: function(
  843. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  844. // fuzz-free, array-based Quaternion SLERP operation
  845. var x0 = src0[ srcOffset0 ],
  846. y0 = src0[ srcOffset0 + 1 ],
  847. z0 = src0[ srcOffset0 + 2 ],
  848. w0 = src0[ srcOffset0 + 3 ],
  849. x1 = src1[ srcOffset1 ],
  850. y1 = src1[ srcOffset1 + 1 ],
  851. z1 = src1[ srcOffset1 + 2 ],
  852. w1 = src1[ srcOffset1 + 3 ];
  853. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  854. var s = 1 - t,
  855. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  856. dir = ( cos >= 0 ? 1 : -1 ),
  857. sqrSin = 1 - cos * cos;
  858. // Skip the Slerp for tiny steps to avoid numeric problems:
  859. if ( sqrSin > Number.EPSILON ) {
  860. var sin = Math.sqrt( sqrSin ),
  861. len = Math.atan2( sin, cos * dir );
  862. s = Math.sin( s * len ) / sin;
  863. t = Math.sin( t * len ) / sin;
  864. }
  865. var tDir = t * dir;
  866. x0 = x0 * s + x1 * tDir;
  867. y0 = y0 * s + y1 * tDir;
  868. z0 = z0 * s + z1 * tDir;
  869. w0 = w0 * s + w1 * tDir;
  870. // Normalize in case we just did a lerp:
  871. if ( s === 1 - t ) {
  872. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  873. x0 *= f;
  874. y0 *= f;
  875. z0 *= f;
  876. w0 *= f;
  877. }
  878. }
  879. dst[ dstOffset ] = x0;
  880. dst[ dstOffset + 1 ] = y0;
  881. dst[ dstOffset + 2 ] = z0;
  882. dst[ dstOffset + 3 ] = w0;
  883. }
  884. } );
  885. // File:src/math/Vector2.js
  886. /**
  887. * @author mrdoob / http://mrdoob.com/
  888. * @author philogb / http://blog.thejit.org/
  889. * @author egraether / http://egraether.com/
  890. * @author zz85 / http://www.lab4games.net/zz85/blog
  891. */
  892. THREE.Vector2 = function ( x, y ) {
  893. this.x = x || 0;
  894. this.y = y || 0;
  895. };
  896. THREE.Vector2.prototype = {
  897. constructor: THREE.Vector2,
  898. get width() { return this.x },
  899. set width( value ) { this.x = value },
  900. get height() { return this.y },
  901. set height( value ) { this.y = value },
  902. //
  903. set: function ( x, y ) {
  904. this.x = x;
  905. this.y = y;
  906. return this;
  907. },
  908. setX: function ( x ) {
  909. this.x = x;
  910. return this;
  911. },
  912. setY: function ( y ) {
  913. this.y = y;
  914. return this;
  915. },
  916. setComponent: function ( index, value ) {
  917. switch ( index ) {
  918. case 0: this.x = value; break;
  919. case 1: this.y = value; break;
  920. default: throw new Error( 'index is out of range: ' + index );
  921. }
  922. },
  923. getComponent: function ( index ) {
  924. switch ( index ) {
  925. case 0: return this.x;
  926. case 1: return this.y;
  927. default: throw new Error( 'index is out of range: ' + index );
  928. }
  929. },
  930. clone: function () {
  931. return new this.constructor( this.x, this.y );
  932. },
  933. copy: function ( v ) {
  934. this.x = v.x;
  935. this.y = v.y;
  936. return this;
  937. },
  938. add: function ( v, w ) {
  939. if ( w !== undefined ) {
  940. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  941. return this.addVectors( v, w );
  942. }
  943. this.x += v.x;
  944. this.y += v.y;
  945. return this;
  946. },
  947. addScalar: function ( s ) {
  948. this.x += s;
  949. this.y += s;
  950. return this;
  951. },
  952. addVectors: function ( a, b ) {
  953. this.x = a.x + b.x;
  954. this.y = a.y + b.y;
  955. return this;
  956. },
  957. addScaledVector: function ( v, s ) {
  958. this.x += v.x * s;
  959. this.y += v.y * s;
  960. return this;
  961. },
  962. sub: function ( v, w ) {
  963. if ( w !== undefined ) {
  964. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  965. return this.subVectors( v, w );
  966. }
  967. this.x -= v.x;
  968. this.y -= v.y;
  969. return this;
  970. },
  971. subScalar: function ( s ) {
  972. this.x -= s;
  973. this.y -= s;
  974. return this;
  975. },
  976. subVectors: function ( a, b ) {
  977. this.x = a.x - b.x;
  978. this.y = a.y - b.y;
  979. return this;
  980. },
  981. multiply: function ( v ) {
  982. this.x *= v.x;
  983. this.y *= v.y;
  984. return this;
  985. },
  986. multiplyScalar: function ( scalar ) {
  987. if ( isFinite( scalar ) ) {
  988. this.x *= scalar;
  989. this.y *= scalar;
  990. } else {
  991. this.x = 0;
  992. this.y = 0;
  993. }
  994. return this;
  995. },
  996. divide: function ( v ) {
  997. this.x /= v.x;
  998. this.y /= v.y;
  999. return this;
  1000. },
  1001. divideScalar: function ( scalar ) {
  1002. return this.multiplyScalar( 1 / scalar );
  1003. },
  1004. min: function ( v ) {
  1005. this.x = Math.min( this.x, v.x );
  1006. this.y = Math.min( this.y, v.y );
  1007. return this;
  1008. },
  1009. max: function ( v ) {
  1010. this.x = Math.max( this.x, v.x );
  1011. this.y = Math.max( this.y, v.y );
  1012. return this;
  1013. },
  1014. clamp: function ( min, max ) {
  1015. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1016. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1017. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1018. return this;
  1019. },
  1020. clampScalar: function () {
  1021. var min, max;
  1022. return function clampScalar( minVal, maxVal ) {
  1023. if ( min === undefined ) {
  1024. min = new THREE.Vector2();
  1025. max = new THREE.Vector2();
  1026. }
  1027. min.set( minVal, minVal );
  1028. max.set( maxVal, maxVal );
  1029. return this.clamp( min, max );
  1030. };
  1031. }(),
  1032. clampLength: function ( min, max ) {
  1033. var length = this.length();
  1034. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1035. return this;
  1036. },
  1037. floor: function () {
  1038. this.x = Math.floor( this.x );
  1039. this.y = Math.floor( this.y );
  1040. return this;
  1041. },
  1042. ceil: function () {
  1043. this.x = Math.ceil( this.x );
  1044. this.y = Math.ceil( this.y );
  1045. return this;
  1046. },
  1047. round: function () {
  1048. this.x = Math.round( this.x );
  1049. this.y = Math.round( this.y );
  1050. return this;
  1051. },
  1052. roundToZero: function () {
  1053. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1054. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1055. return this;
  1056. },
  1057. negate: function () {
  1058. this.x = - this.x;
  1059. this.y = - this.y;
  1060. return this;
  1061. },
  1062. dot: function ( v ) {
  1063. return this.x * v.x + this.y * v.y;
  1064. },
  1065. lengthSq: function () {
  1066. return this.x * this.x + this.y * this.y;
  1067. },
  1068. length: function () {
  1069. return Math.sqrt( this.x * this.x + this.y * this.y );
  1070. },
  1071. lengthManhattan: function() {
  1072. return Math.abs( this.x ) + Math.abs( this.y );
  1073. },
  1074. normalize: function () {
  1075. return this.divideScalar( this.length() );
  1076. },
  1077. distanceTo: function ( v ) {
  1078. return Math.sqrt( this.distanceToSquared( v ) );
  1079. },
  1080. distanceToSquared: function ( v ) {
  1081. var dx = this.x - v.x, dy = this.y - v.y;
  1082. return dx * dx + dy * dy;
  1083. },
  1084. setLength: function ( length ) {
  1085. return this.multiplyScalar( length / this.length() );
  1086. },
  1087. lerp: function ( v, alpha ) {
  1088. this.x += ( v.x - this.x ) * alpha;
  1089. this.y += ( v.y - this.y ) * alpha;
  1090. return this;
  1091. },
  1092. lerpVectors: function ( v1, v2, alpha ) {
  1093. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1094. return this;
  1095. },
  1096. equals: function ( v ) {
  1097. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1098. },
  1099. fromArray: function ( array, offset ) {
  1100. if ( offset === undefined ) offset = 0;
  1101. this.x = array[ offset ];
  1102. this.y = array[ offset + 1 ];
  1103. return this;
  1104. },
  1105. toArray: function ( array, offset ) {
  1106. if ( array === undefined ) array = [];
  1107. if ( offset === undefined ) offset = 0;
  1108. array[ offset ] = this.x;
  1109. array[ offset + 1 ] = this.y;
  1110. return array;
  1111. },
  1112. fromAttribute: function ( attribute, index, offset ) {
  1113. if ( offset === undefined ) offset = 0;
  1114. index = index * attribute.itemSize + offset;
  1115. this.x = attribute.array[ index ];
  1116. this.y = attribute.array[ index + 1 ];
  1117. return this;
  1118. },
  1119. rotateAround: function ( center, angle ) {
  1120. var c = Math.cos( angle ), s = Math.sin( angle );
  1121. var x = this.x - center.x;
  1122. var y = this.y - center.y;
  1123. this.x = x * c - y * s + center.x;
  1124. this.y = x * s + y * c + center.y;
  1125. return this;
  1126. }
  1127. };
  1128. // File:src/math/Vector3.js
  1129. /**
  1130. * @author mrdoob / http://mrdoob.com/
  1131. * @author *kile / http://kile.stravaganza.org/
  1132. * @author philogb / http://blog.thejit.org/
  1133. * @author mikael emtinger / http://gomo.se/
  1134. * @author egraether / http://egraether.com/
  1135. * @author WestLangley / http://github.com/WestLangley
  1136. */
  1137. THREE.Vector3 = function ( x, y, z ) {
  1138. this.x = x || 0;
  1139. this.y = y || 0;
  1140. this.z = z || 0;
  1141. };
  1142. THREE.Vector3.prototype = {
  1143. constructor: THREE.Vector3,
  1144. set: function ( x, y, z ) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. return this;
  1149. },
  1150. setX: function ( x ) {
  1151. this.x = x;
  1152. return this;
  1153. },
  1154. setY: function ( y ) {
  1155. this.y = y;
  1156. return this;
  1157. },
  1158. setZ: function ( z ) {
  1159. this.z = z;
  1160. return this;
  1161. },
  1162. setComponent: function ( index, value ) {
  1163. switch ( index ) {
  1164. case 0: this.x = value; break;
  1165. case 1: this.y = value; break;
  1166. case 2: this.z = value; break;
  1167. default: throw new Error( 'index is out of range: ' + index );
  1168. }
  1169. },
  1170. getComponent: function ( index ) {
  1171. switch ( index ) {
  1172. case 0: return this.x;
  1173. case 1: return this.y;
  1174. case 2: return this.z;
  1175. default: throw new Error( 'index is out of range: ' + index );
  1176. }
  1177. },
  1178. clone: function () {
  1179. return new this.constructor( this.x, this.y, this.z );
  1180. },
  1181. copy: function ( v ) {
  1182. this.x = v.x;
  1183. this.y = v.y;
  1184. this.z = v.z;
  1185. return this;
  1186. },
  1187. add: function ( v, w ) {
  1188. if ( w !== undefined ) {
  1189. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1190. return this.addVectors( v, w );
  1191. }
  1192. this.x += v.x;
  1193. this.y += v.y;
  1194. this.z += v.z;
  1195. return this;
  1196. },
  1197. addScalar: function ( s ) {
  1198. this.x += s;
  1199. this.y += s;
  1200. this.z += s;
  1201. return this;
  1202. },
  1203. addVectors: function ( a, b ) {
  1204. this.x = a.x + b.x;
  1205. this.y = a.y + b.y;
  1206. this.z = a.z + b.z;
  1207. return this;
  1208. },
  1209. addScaledVector: function ( v, s ) {
  1210. this.x += v.x * s;
  1211. this.y += v.y * s;
  1212. this.z += v.z * s;
  1213. return this;
  1214. },
  1215. sub: function ( v, w ) {
  1216. if ( w !== undefined ) {
  1217. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1218. return this.subVectors( v, w );
  1219. }
  1220. this.x -= v.x;
  1221. this.y -= v.y;
  1222. this.z -= v.z;
  1223. return this;
  1224. },
  1225. subScalar: function ( s ) {
  1226. this.x -= s;
  1227. this.y -= s;
  1228. this.z -= s;
  1229. return this;
  1230. },
  1231. subVectors: function ( a, b ) {
  1232. this.x = a.x - b.x;
  1233. this.y = a.y - b.y;
  1234. this.z = a.z - b.z;
  1235. return this;
  1236. },
  1237. multiply: function ( v, w ) {
  1238. if ( w !== undefined ) {
  1239. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1240. return this.multiplyVectors( v, w );
  1241. }
  1242. this.x *= v.x;
  1243. this.y *= v.y;
  1244. this.z *= v.z;
  1245. return this;
  1246. },
  1247. multiplyScalar: function ( scalar ) {
  1248. if ( isFinite( scalar ) ) {
  1249. this.x *= scalar;
  1250. this.y *= scalar;
  1251. this.z *= scalar;
  1252. } else {
  1253. this.x = 0;
  1254. this.y = 0;
  1255. this.z = 0;
  1256. }
  1257. return this;
  1258. },
  1259. multiplyVectors: function ( a, b ) {
  1260. this.x = a.x * b.x;
  1261. this.y = a.y * b.y;
  1262. this.z = a.z * b.z;
  1263. return this;
  1264. },
  1265. applyEuler: function () {
  1266. var quaternion;
  1267. return function applyEuler( euler ) {
  1268. if ( euler instanceof THREE.Euler === false ) {
  1269. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1270. }
  1271. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1272. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1273. return this;
  1274. };
  1275. }(),
  1276. applyAxisAngle: function () {
  1277. var quaternion;
  1278. return function applyAxisAngle( axis, angle ) {
  1279. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1280. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1281. return this;
  1282. };
  1283. }(),
  1284. applyMatrix3: function ( m ) {
  1285. var x = this.x;
  1286. var y = this.y;
  1287. var z = this.z;
  1288. var e = m.elements;
  1289. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1290. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1291. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1292. return this;
  1293. },
  1294. applyMatrix4: function ( m ) {
  1295. // input: THREE.Matrix4 affine matrix
  1296. var x = this.x, y = this.y, z = this.z;
  1297. var e = m.elements;
  1298. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1299. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1300. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1301. return this;
  1302. },
  1303. applyProjection: function ( m ) {
  1304. // input: THREE.Matrix4 projection matrix
  1305. var x = this.x, y = this.y, z = this.z;
  1306. var e = m.elements;
  1307. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1308. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1309. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1310. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1311. return this;
  1312. },
  1313. applyQuaternion: function ( q ) {
  1314. var x = this.x;
  1315. var y = this.y;
  1316. var z = this.z;
  1317. var qx = q.x;
  1318. var qy = q.y;
  1319. var qz = q.z;
  1320. var qw = q.w;
  1321. // calculate quat * vector
  1322. var ix = qw * x + qy * z - qz * y;
  1323. var iy = qw * y + qz * x - qx * z;
  1324. var iz = qw * z + qx * y - qy * x;
  1325. var iw = - qx * x - qy * y - qz * z;
  1326. // calculate result * inverse quat
  1327. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1328. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1329. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1330. return this;
  1331. },
  1332. project: function () {
  1333. var matrix;
  1334. return function project( camera ) {
  1335. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1336. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1337. return this.applyProjection( matrix );
  1338. };
  1339. }(),
  1340. unproject: function () {
  1341. var matrix;
  1342. return function unproject( camera ) {
  1343. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1344. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1345. return this.applyProjection( matrix );
  1346. };
  1347. }(),
  1348. transformDirection: function ( m ) {
  1349. // input: THREE.Matrix4 affine matrix
  1350. // vector interpreted as a direction
  1351. var x = this.x, y = this.y, z = this.z;
  1352. var e = m.elements;
  1353. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1354. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1355. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1356. this.normalize();
  1357. return this;
  1358. },
  1359. divide: function ( v ) {
  1360. this.x /= v.x;
  1361. this.y /= v.y;
  1362. this.z /= v.z;
  1363. return this;
  1364. },
  1365. divideScalar: function ( scalar ) {
  1366. return this.multiplyScalar( 1 / scalar );
  1367. },
  1368. min: function ( v ) {
  1369. this.x = Math.min( this.x, v.x );
  1370. this.y = Math.min( this.y, v.y );
  1371. this.z = Math.min( this.z, v.z );
  1372. return this;
  1373. },
  1374. max: function ( v ) {
  1375. this.x = Math.max( this.x, v.x );
  1376. this.y = Math.max( this.y, v.y );
  1377. this.z = Math.max( this.z, v.z );
  1378. return this;
  1379. },
  1380. clamp: function ( min, max ) {
  1381. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1382. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1383. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1384. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1385. return this;
  1386. },
  1387. clampScalar: function () {
  1388. var min, max;
  1389. return function clampScalar( minVal, maxVal ) {
  1390. if ( min === undefined ) {
  1391. min = new THREE.Vector3();
  1392. max = new THREE.Vector3();
  1393. }
  1394. min.set( minVal, minVal, minVal );
  1395. max.set( maxVal, maxVal, maxVal );
  1396. return this.clamp( min, max );
  1397. };
  1398. }(),
  1399. clampLength: function ( min, max ) {
  1400. var length = this.length();
  1401. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1402. return this;
  1403. },
  1404. floor: function () {
  1405. this.x = Math.floor( this.x );
  1406. this.y = Math.floor( this.y );
  1407. this.z = Math.floor( this.z );
  1408. return this;
  1409. },
  1410. ceil: function () {
  1411. this.x = Math.ceil( this.x );
  1412. this.y = Math.ceil( this.y );
  1413. this.z = Math.ceil( this.z );
  1414. return this;
  1415. },
  1416. round: function () {
  1417. this.x = Math.round( this.x );
  1418. this.y = Math.round( this.y );
  1419. this.z = Math.round( this.z );
  1420. return this;
  1421. },
  1422. roundToZero: function () {
  1423. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1424. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1425. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1426. return this;
  1427. },
  1428. negate: function () {
  1429. this.x = - this.x;
  1430. this.y = - this.y;
  1431. this.z = - this.z;
  1432. return this;
  1433. },
  1434. dot: function ( v ) {
  1435. return this.x * v.x + this.y * v.y + this.z * v.z;
  1436. },
  1437. lengthSq: function () {
  1438. return this.x * this.x + this.y * this.y + this.z * this.z;
  1439. },
  1440. length: function () {
  1441. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1442. },
  1443. lengthManhattan: function () {
  1444. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1445. },
  1446. normalize: function () {
  1447. return this.divideScalar( this.length() );
  1448. },
  1449. setLength: function ( length ) {
  1450. return this.multiplyScalar( length / this.length() );
  1451. },
  1452. lerp: function ( v, alpha ) {
  1453. this.x += ( v.x - this.x ) * alpha;
  1454. this.y += ( v.y - this.y ) * alpha;
  1455. this.z += ( v.z - this.z ) * alpha;
  1456. return this;
  1457. },
  1458. lerpVectors: function ( v1, v2, alpha ) {
  1459. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1460. return this;
  1461. },
  1462. cross: function ( v, w ) {
  1463. if ( w !== undefined ) {
  1464. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1465. return this.crossVectors( v, w );
  1466. }
  1467. var x = this.x, y = this.y, z = this.z;
  1468. this.x = y * v.z - z * v.y;
  1469. this.y = z * v.x - x * v.z;
  1470. this.z = x * v.y - y * v.x;
  1471. return this;
  1472. },
  1473. crossVectors: function ( a, b ) {
  1474. var ax = a.x, ay = a.y, az = a.z;
  1475. var bx = b.x, by = b.y, bz = b.z;
  1476. this.x = ay * bz - az * by;
  1477. this.y = az * bx - ax * bz;
  1478. this.z = ax * by - ay * bx;
  1479. return this;
  1480. },
  1481. projectOnVector: function () {
  1482. var v1, dot;
  1483. return function projectOnVector( vector ) {
  1484. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1485. v1.copy( vector ).normalize();
  1486. dot = this.dot( v1 );
  1487. return this.copy( v1 ).multiplyScalar( dot );
  1488. };
  1489. }(),
  1490. projectOnPlane: function () {
  1491. var v1;
  1492. return function projectOnPlane( planeNormal ) {
  1493. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1494. v1.copy( this ).projectOnVector( planeNormal );
  1495. return this.sub( v1 );
  1496. }
  1497. }(),
  1498. reflect: function () {
  1499. // reflect incident vector off plane orthogonal to normal
  1500. // normal is assumed to have unit length
  1501. var v1;
  1502. return function reflect( normal ) {
  1503. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1504. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1505. }
  1506. }(),
  1507. angleTo: function ( v ) {
  1508. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1509. // clamp, to handle numerical problems
  1510. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1511. },
  1512. distanceTo: function ( v ) {
  1513. return Math.sqrt( this.distanceToSquared( v ) );
  1514. },
  1515. distanceToSquared: function ( v ) {
  1516. var dx = this.x - v.x;
  1517. var dy = this.y - v.y;
  1518. var dz = this.z - v.z;
  1519. return dx * dx + dy * dy + dz * dz;
  1520. },
  1521. setFromMatrixPosition: function ( m ) {
  1522. this.x = m.elements[ 12 ];
  1523. this.y = m.elements[ 13 ];
  1524. this.z = m.elements[ 14 ];
  1525. return this;
  1526. },
  1527. setFromMatrixScale: function ( m ) {
  1528. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1529. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1530. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1531. this.x = sx;
  1532. this.y = sy;
  1533. this.z = sz;
  1534. return this;
  1535. },
  1536. setFromMatrixColumn: function ( index, matrix ) {
  1537. var offset = index * 4;
  1538. var me = matrix.elements;
  1539. this.x = me[ offset ];
  1540. this.y = me[ offset + 1 ];
  1541. this.z = me[ offset + 2 ];
  1542. return this;
  1543. },
  1544. equals: function ( v ) {
  1545. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1546. },
  1547. fromArray: function ( array, offset ) {
  1548. if ( offset === undefined ) offset = 0;
  1549. this.x = array[ offset ];
  1550. this.y = array[ offset + 1 ];
  1551. this.z = array[ offset + 2 ];
  1552. return this;
  1553. },
  1554. toArray: function ( array, offset ) {
  1555. if ( array === undefined ) array = [];
  1556. if ( offset === undefined ) offset = 0;
  1557. array[ offset ] = this.x;
  1558. array[ offset + 1 ] = this.y;
  1559. array[ offset + 2 ] = this.z;
  1560. return array;
  1561. },
  1562. fromAttribute: function ( attribute, index, offset ) {
  1563. if ( offset === undefined ) offset = 0;
  1564. index = index * attribute.itemSize + offset;
  1565. this.x = attribute.array[ index ];
  1566. this.y = attribute.array[ index + 1 ];
  1567. this.z = attribute.array[ index + 2 ];
  1568. return this;
  1569. }
  1570. };
  1571. // File:src/math/Vector4.js
  1572. /**
  1573. * @author supereggbert / http://www.paulbrunt.co.uk/
  1574. * @author philogb / http://blog.thejit.org/
  1575. * @author mikael emtinger / http://gomo.se/
  1576. * @author egraether / http://egraether.com/
  1577. * @author WestLangley / http://github.com/WestLangley
  1578. */
  1579. THREE.Vector4 = function ( x, y, z, w ) {
  1580. this.x = x || 0;
  1581. this.y = y || 0;
  1582. this.z = z || 0;
  1583. this.w = ( w !== undefined ) ? w : 1;
  1584. };
  1585. THREE.Vector4.prototype = {
  1586. constructor: THREE.Vector4,
  1587. set: function ( x, y, z, w ) {
  1588. this.x = x;
  1589. this.y = y;
  1590. this.z = z;
  1591. this.w = w;
  1592. return this;
  1593. },
  1594. setX: function ( x ) {
  1595. this.x = x;
  1596. return this;
  1597. },
  1598. setY: function ( y ) {
  1599. this.y = y;
  1600. return this;
  1601. },
  1602. setZ: function ( z ) {
  1603. this.z = z;
  1604. return this;
  1605. },
  1606. setW: function ( w ) {
  1607. this.w = w;
  1608. return this;
  1609. },
  1610. setComponent: function ( index, value ) {
  1611. switch ( index ) {
  1612. case 0: this.x = value; break;
  1613. case 1: this.y = value; break;
  1614. case 2: this.z = value; break;
  1615. case 3: this.w = value; break;
  1616. default: throw new Error( 'index is out of range: ' + index );
  1617. }
  1618. },
  1619. getComponent: function ( index ) {
  1620. switch ( index ) {
  1621. case 0: return this.x;
  1622. case 1: return this.y;
  1623. case 2: return this.z;
  1624. case 3: return this.w;
  1625. default: throw new Error( 'index is out of range: ' + index );
  1626. }
  1627. },
  1628. clone: function () {
  1629. return new this.constructor( this.x, this.y, this.z, this.w );
  1630. },
  1631. copy: function ( v ) {
  1632. this.x = v.x;
  1633. this.y = v.y;
  1634. this.z = v.z;
  1635. this.w = ( v.w !== undefined ) ? v.w : 1;
  1636. return this;
  1637. },
  1638. add: function ( v, w ) {
  1639. if ( w !== undefined ) {
  1640. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1641. return this.addVectors( v, w );
  1642. }
  1643. this.x += v.x;
  1644. this.y += v.y;
  1645. this.z += v.z;
  1646. this.w += v.w;
  1647. return this;
  1648. },
  1649. addScalar: function ( s ) {
  1650. this.x += s;
  1651. this.y += s;
  1652. this.z += s;
  1653. this.w += s;
  1654. return this;
  1655. },
  1656. addVectors: function ( a, b ) {
  1657. this.x = a.x + b.x;
  1658. this.y = a.y + b.y;
  1659. this.z = a.z + b.z;
  1660. this.w = a.w + b.w;
  1661. return this;
  1662. },
  1663. addScaledVector: function ( v, s ) {
  1664. this.x += v.x * s;
  1665. this.y += v.y * s;
  1666. this.z += v.z * s;
  1667. this.w += v.w * s;
  1668. return this;
  1669. },
  1670. sub: function ( v, w ) {
  1671. if ( w !== undefined ) {
  1672. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1673. return this.subVectors( v, w );
  1674. }
  1675. this.x -= v.x;
  1676. this.y -= v.y;
  1677. this.z -= v.z;
  1678. this.w -= v.w;
  1679. return this;
  1680. },
  1681. subScalar: function ( s ) {
  1682. this.x -= s;
  1683. this.y -= s;
  1684. this.z -= s;
  1685. this.w -= s;
  1686. return this;
  1687. },
  1688. subVectors: function ( a, b ) {
  1689. this.x = a.x - b.x;
  1690. this.y = a.y - b.y;
  1691. this.z = a.z - b.z;
  1692. this.w = a.w - b.w;
  1693. return this;
  1694. },
  1695. multiplyScalar: function ( scalar ) {
  1696. if ( isFinite( scalar ) ) {
  1697. this.x *= scalar;
  1698. this.y *= scalar;
  1699. this.z *= scalar;
  1700. this.w *= scalar;
  1701. } else {
  1702. this.x = 0;
  1703. this.y = 0;
  1704. this.z = 0;
  1705. this.w = 0;
  1706. }
  1707. return this;
  1708. },
  1709. applyMatrix4: function ( m ) {
  1710. var x = this.x;
  1711. var y = this.y;
  1712. var z = this.z;
  1713. var w = this.w;
  1714. var e = m.elements;
  1715. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1716. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1717. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1718. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1719. return this;
  1720. },
  1721. divideScalar: function ( scalar ) {
  1722. return this.multiplyScalar( 1 / scalar );
  1723. },
  1724. setAxisAngleFromQuaternion: function ( q ) {
  1725. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1726. // q is assumed to be normalized
  1727. this.w = 2 * Math.acos( q.w );
  1728. var s = Math.sqrt( 1 - q.w * q.w );
  1729. if ( s < 0.0001 ) {
  1730. this.x = 1;
  1731. this.y = 0;
  1732. this.z = 0;
  1733. } else {
  1734. this.x = q.x / s;
  1735. this.y = q.y / s;
  1736. this.z = q.z / s;
  1737. }
  1738. return this;
  1739. },
  1740. setAxisAngleFromRotationMatrix: function ( m ) {
  1741. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1742. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1743. var angle, x, y, z, // variables for result
  1744. epsilon = 0.01, // margin to allow for rounding errors
  1745. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1746. te = m.elements,
  1747. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1748. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1749. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1750. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1751. && ( Math.abs( m13 - m31 ) < epsilon )
  1752. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1753. // singularity found
  1754. // first check for identity matrix which must have +1 for all terms
  1755. // in leading diagonal and zero in other terms
  1756. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1757. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1758. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1759. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1760. // this singularity is identity matrix so angle = 0
  1761. this.set( 1, 0, 0, 0 );
  1762. return this; // zero angle, arbitrary axis
  1763. }
  1764. // otherwise this singularity is angle = 180
  1765. angle = Math.PI;
  1766. var xx = ( m11 + 1 ) / 2;
  1767. var yy = ( m22 + 1 ) / 2;
  1768. var zz = ( m33 + 1 ) / 2;
  1769. var xy = ( m12 + m21 ) / 4;
  1770. var xz = ( m13 + m31 ) / 4;
  1771. var yz = ( m23 + m32 ) / 4;
  1772. if ( ( xx > yy ) && ( xx > zz ) ) {
  1773. // m11 is the largest diagonal term
  1774. if ( xx < epsilon ) {
  1775. x = 0;
  1776. y = 0.707106781;
  1777. z = 0.707106781;
  1778. } else {
  1779. x = Math.sqrt( xx );
  1780. y = xy / x;
  1781. z = xz / x;
  1782. }
  1783. } else if ( yy > zz ) {
  1784. // m22 is the largest diagonal term
  1785. if ( yy < epsilon ) {
  1786. x = 0.707106781;
  1787. y = 0;
  1788. z = 0.707106781;
  1789. } else {
  1790. y = Math.sqrt( yy );
  1791. x = xy / y;
  1792. z = yz / y;
  1793. }
  1794. } else {
  1795. // m33 is the largest diagonal term so base result on this
  1796. if ( zz < epsilon ) {
  1797. x = 0.707106781;
  1798. y = 0.707106781;
  1799. z = 0;
  1800. } else {
  1801. z = Math.sqrt( zz );
  1802. x = xz / z;
  1803. y = yz / z;
  1804. }
  1805. }
  1806. this.set( x, y, z, angle );
  1807. return this; // return 180 deg rotation
  1808. }
  1809. // as we have reached here there are no singularities so we can handle normally
  1810. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1811. + ( m13 - m31 ) * ( m13 - m31 )
  1812. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1813. if ( Math.abs( s ) < 0.001 ) s = 1;
  1814. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1815. // caught by singularity test above, but I've left it in just in case
  1816. this.x = ( m32 - m23 ) / s;
  1817. this.y = ( m13 - m31 ) / s;
  1818. this.z = ( m21 - m12 ) / s;
  1819. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1820. return this;
  1821. },
  1822. min: function ( v ) {
  1823. this.x = Math.min( this.x, v.x );
  1824. this.y = Math.min( this.y, v.y );
  1825. this.z = Math.min( this.z, v.z );
  1826. this.w = Math.min( this.w, v.w );
  1827. return this;
  1828. },
  1829. max: function ( v ) {
  1830. this.x = Math.max( this.x, v.x );
  1831. this.y = Math.max( this.y, v.y );
  1832. this.z = Math.max( this.z, v.z );
  1833. this.w = Math.max( this.w, v.w );
  1834. return this;
  1835. },
  1836. clamp: function ( min, max ) {
  1837. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1838. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1839. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1840. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1841. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1842. return this;
  1843. },
  1844. clampScalar: function () {
  1845. var min, max;
  1846. return function clampScalar( minVal, maxVal ) {
  1847. if ( min === undefined ) {
  1848. min = new THREE.Vector4();
  1849. max = new THREE.Vector4();
  1850. }
  1851. min.set( minVal, minVal, minVal, minVal );
  1852. max.set( maxVal, maxVal, maxVal, maxVal );
  1853. return this.clamp( min, max );
  1854. };
  1855. }(),
  1856. floor: function () {
  1857. this.x = Math.floor( this.x );
  1858. this.y = Math.floor( this.y );
  1859. this.z = Math.floor( this.z );
  1860. this.w = Math.floor( this.w );
  1861. return this;
  1862. },
  1863. ceil: function () {
  1864. this.x = Math.ceil( this.x );
  1865. this.y = Math.ceil( this.y );
  1866. this.z = Math.ceil( this.z );
  1867. this.w = Math.ceil( this.w );
  1868. return this;
  1869. },
  1870. round: function () {
  1871. this.x = Math.round( this.x );
  1872. this.y = Math.round( this.y );
  1873. this.z = Math.round( this.z );
  1874. this.w = Math.round( this.w );
  1875. return this;
  1876. },
  1877. roundToZero: function () {
  1878. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1879. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1880. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1881. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1882. return this;
  1883. },
  1884. negate: function () {
  1885. this.x = - this.x;
  1886. this.y = - this.y;
  1887. this.z = - this.z;
  1888. this.w = - this.w;
  1889. return this;
  1890. },
  1891. dot: function ( v ) {
  1892. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1893. },
  1894. lengthSq: function () {
  1895. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1896. },
  1897. length: function () {
  1898. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1899. },
  1900. lengthManhattan: function () {
  1901. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1902. },
  1903. normalize: function () {
  1904. return this.divideScalar( this.length() );
  1905. },
  1906. setLength: function ( length ) {
  1907. return this.multiplyScalar( length / this.length() );
  1908. },
  1909. lerp: function ( v, alpha ) {
  1910. this.x += ( v.x - this.x ) * alpha;
  1911. this.y += ( v.y - this.y ) * alpha;
  1912. this.z += ( v.z - this.z ) * alpha;
  1913. this.w += ( v.w - this.w ) * alpha;
  1914. return this;
  1915. },
  1916. lerpVectors: function ( v1, v2, alpha ) {
  1917. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1918. return this;
  1919. },
  1920. equals: function ( v ) {
  1921. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1922. },
  1923. fromArray: function ( array, offset ) {
  1924. if ( offset === undefined ) offset = 0;
  1925. this.x = array[ offset ];
  1926. this.y = array[ offset + 1 ];
  1927. this.z = array[ offset + 2 ];
  1928. this.w = array[ offset + 3 ];
  1929. return this;
  1930. },
  1931. toArray: function ( array, offset ) {
  1932. if ( array === undefined ) array = [];
  1933. if ( offset === undefined ) offset = 0;
  1934. array[ offset ] = this.x;
  1935. array[ offset + 1 ] = this.y;
  1936. array[ offset + 2 ] = this.z;
  1937. array[ offset + 3 ] = this.w;
  1938. return array;
  1939. },
  1940. fromAttribute: function ( attribute, index, offset ) {
  1941. if ( offset === undefined ) offset = 0;
  1942. index = index * attribute.itemSize + offset;
  1943. this.x = attribute.array[ index ];
  1944. this.y = attribute.array[ index + 1 ];
  1945. this.z = attribute.array[ index + 2 ];
  1946. this.w = attribute.array[ index + 3 ];
  1947. return this;
  1948. }
  1949. };
  1950. // File:src/math/Euler.js
  1951. /**
  1952. * @author mrdoob / http://mrdoob.com/
  1953. * @author WestLangley / http://github.com/WestLangley
  1954. * @author bhouston / http://clara.io
  1955. */
  1956. THREE.Euler = function ( x, y, z, order ) {
  1957. this._x = x || 0;
  1958. this._y = y || 0;
  1959. this._z = z || 0;
  1960. this._order = order || THREE.Euler.DefaultOrder;
  1961. };
  1962. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1963. THREE.Euler.DefaultOrder = 'XYZ';
  1964. THREE.Euler.prototype = {
  1965. constructor: THREE.Euler,
  1966. get x () {
  1967. return this._x;
  1968. },
  1969. set x ( value ) {
  1970. this._x = value;
  1971. this.onChangeCallback();
  1972. },
  1973. get y () {
  1974. return this._y;
  1975. },
  1976. set y ( value ) {
  1977. this._y = value;
  1978. this.onChangeCallback();
  1979. },
  1980. get z () {
  1981. return this._z;
  1982. },
  1983. set z ( value ) {
  1984. this._z = value;
  1985. this.onChangeCallback();
  1986. },
  1987. get order () {
  1988. return this._order;
  1989. },
  1990. set order ( value ) {
  1991. this._order = value;
  1992. this.onChangeCallback();
  1993. },
  1994. set: function ( x, y, z, order ) {
  1995. this._x = x;
  1996. this._y = y;
  1997. this._z = z;
  1998. this._order = order || this._order;
  1999. this.onChangeCallback();
  2000. return this;
  2001. },
  2002. clone: function () {
  2003. return new this.constructor( this._x, this._y, this._z, this._order);
  2004. },
  2005. copy: function ( euler ) {
  2006. this._x = euler._x;
  2007. this._y = euler._y;
  2008. this._z = euler._z;
  2009. this._order = euler._order;
  2010. this.onChangeCallback();
  2011. return this;
  2012. },
  2013. setFromRotationMatrix: function ( m, order, update ) {
  2014. var clamp = THREE.Math.clamp;
  2015. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2016. var te = m.elements;
  2017. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2018. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2019. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2020. order = order || this._order;
  2021. if ( order === 'XYZ' ) {
  2022. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2023. if ( Math.abs( m13 ) < 0.99999 ) {
  2024. this._x = Math.atan2( - m23, m33 );
  2025. this._z = Math.atan2( - m12, m11 );
  2026. } else {
  2027. this._x = Math.atan2( m32, m22 );
  2028. this._z = 0;
  2029. }
  2030. } else if ( order === 'YXZ' ) {
  2031. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2032. if ( Math.abs( m23 ) < 0.99999 ) {
  2033. this._y = Math.atan2( m13, m33 );
  2034. this._z = Math.atan2( m21, m22 );
  2035. } else {
  2036. this._y = Math.atan2( - m31, m11 );
  2037. this._z = 0;
  2038. }
  2039. } else if ( order === 'ZXY' ) {
  2040. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2041. if ( Math.abs( m32 ) < 0.99999 ) {
  2042. this._y = Math.atan2( - m31, m33 );
  2043. this._z = Math.atan2( - m12, m22 );
  2044. } else {
  2045. this._y = 0;
  2046. this._z = Math.atan2( m21, m11 );
  2047. }
  2048. } else if ( order === 'ZYX' ) {
  2049. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2050. if ( Math.abs( m31 ) < 0.99999 ) {
  2051. this._x = Math.atan2( m32, m33 );
  2052. this._z = Math.atan2( m21, m11 );
  2053. } else {
  2054. this._x = 0;
  2055. this._z = Math.atan2( - m12, m22 );
  2056. }
  2057. } else if ( order === 'YZX' ) {
  2058. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2059. if ( Math.abs( m21 ) < 0.99999 ) {
  2060. this._x = Math.atan2( - m23, m22 );
  2061. this._y = Math.atan2( - m31, m11 );
  2062. } else {
  2063. this._x = 0;
  2064. this._y = Math.atan2( m13, m33 );
  2065. }
  2066. } else if ( order === 'XZY' ) {
  2067. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2068. if ( Math.abs( m12 ) < 0.99999 ) {
  2069. this._x = Math.atan2( m32, m22 );
  2070. this._y = Math.atan2( m13, m11 );
  2071. } else {
  2072. this._x = Math.atan2( - m23, m33 );
  2073. this._y = 0;
  2074. }
  2075. } else {
  2076. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2077. }
  2078. this._order = order;
  2079. if ( update !== false ) this.onChangeCallback();
  2080. return this;
  2081. },
  2082. setFromQuaternion: function () {
  2083. var matrix;
  2084. return function ( q, order, update ) {
  2085. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2086. matrix.makeRotationFromQuaternion( q );
  2087. this.setFromRotationMatrix( matrix, order, update );
  2088. return this;
  2089. };
  2090. }(),
  2091. setFromVector3: function ( v, order ) {
  2092. return this.set( v.x, v.y, v.z, order || this._order );
  2093. },
  2094. reorder: function () {
  2095. // WARNING: this discards revolution information -bhouston
  2096. var q = new THREE.Quaternion();
  2097. return function ( newOrder ) {
  2098. q.setFromEuler( this );
  2099. this.setFromQuaternion( q, newOrder );
  2100. };
  2101. }(),
  2102. equals: function ( euler ) {
  2103. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2104. },
  2105. fromArray: function ( array ) {
  2106. this._x = array[ 0 ];
  2107. this._y = array[ 1 ];
  2108. this._z = array[ 2 ];
  2109. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2110. this.onChangeCallback();
  2111. return this;
  2112. },
  2113. toArray: function ( array, offset ) {
  2114. if ( array === undefined ) array = [];
  2115. if ( offset === undefined ) offset = 0;
  2116. array[ offset ] = this._x;
  2117. array[ offset + 1 ] = this._y;
  2118. array[ offset + 2 ] = this._z;
  2119. array[ offset + 3 ] = this._order;
  2120. return array;
  2121. },
  2122. toVector3: function ( optionalResult ) {
  2123. if ( optionalResult ) {
  2124. return optionalResult.set( this._x, this._y, this._z );
  2125. } else {
  2126. return new THREE.Vector3( this._x, this._y, this._z );
  2127. }
  2128. },
  2129. onChange: function ( callback ) {
  2130. this.onChangeCallback = callback;
  2131. return this;
  2132. },
  2133. onChangeCallback: function () {}
  2134. };
  2135. // File:src/math/Line3.js
  2136. /**
  2137. * @author bhouston / http://clara.io
  2138. */
  2139. THREE.Line3 = function ( start, end ) {
  2140. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2141. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2142. };
  2143. THREE.Line3.prototype = {
  2144. constructor: THREE.Line3,
  2145. set: function ( start, end ) {
  2146. this.start.copy( start );
  2147. this.end.copy( end );
  2148. return this;
  2149. },
  2150. clone: function () {
  2151. return new this.constructor().copy( this );
  2152. },
  2153. copy: function ( line ) {
  2154. this.start.copy( line.start );
  2155. this.end.copy( line.end );
  2156. return this;
  2157. },
  2158. center: function ( optionalTarget ) {
  2159. var result = optionalTarget || new THREE.Vector3();
  2160. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2161. },
  2162. delta: function ( optionalTarget ) {
  2163. var result = optionalTarget || new THREE.Vector3();
  2164. return result.subVectors( this.end, this.start );
  2165. },
  2166. distanceSq: function () {
  2167. return this.start.distanceToSquared( this.end );
  2168. },
  2169. distance: function () {
  2170. return this.start.distanceTo( this.end );
  2171. },
  2172. at: function ( t, optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Vector3();
  2174. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2175. },
  2176. closestPointToPointParameter: function () {
  2177. var startP = new THREE.Vector3();
  2178. var startEnd = new THREE.Vector3();
  2179. return function ( point, clampToLine ) {
  2180. startP.subVectors( point, this.start );
  2181. startEnd.subVectors( this.end, this.start );
  2182. var startEnd2 = startEnd.dot( startEnd );
  2183. var startEnd_startP = startEnd.dot( startP );
  2184. var t = startEnd_startP / startEnd2;
  2185. if ( clampToLine ) {
  2186. t = THREE.Math.clamp( t, 0, 1 );
  2187. }
  2188. return t;
  2189. };
  2190. }(),
  2191. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2192. var t = this.closestPointToPointParameter( point, clampToLine );
  2193. var result = optionalTarget || new THREE.Vector3();
  2194. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2195. },
  2196. applyMatrix4: function ( matrix ) {
  2197. this.start.applyMatrix4( matrix );
  2198. this.end.applyMatrix4( matrix );
  2199. return this;
  2200. },
  2201. equals: function ( line ) {
  2202. return line.start.equals( this.start ) && line.end.equals( this.end );
  2203. }
  2204. };
  2205. // File:src/math/Box2.js
  2206. /**
  2207. * @author bhouston / http://clara.io
  2208. */
  2209. THREE.Box2 = function ( min, max ) {
  2210. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2211. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2212. };
  2213. THREE.Box2.prototype = {
  2214. constructor: THREE.Box2,
  2215. set: function ( min, max ) {
  2216. this.min.copy( min );
  2217. this.max.copy( max );
  2218. return this;
  2219. },
  2220. setFromPoints: function ( points ) {
  2221. this.makeEmpty();
  2222. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2223. this.expandByPoint( points[ i ] )
  2224. }
  2225. return this;
  2226. },
  2227. setFromCenterAndSize: function () {
  2228. var v1 = new THREE.Vector2();
  2229. return function ( center, size ) {
  2230. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2231. this.min.copy( center ).sub( halfSize );
  2232. this.max.copy( center ).add( halfSize );
  2233. return this;
  2234. };
  2235. }(),
  2236. clone: function () {
  2237. return new this.constructor().copy( this );
  2238. },
  2239. copy: function ( box ) {
  2240. this.min.copy( box.min );
  2241. this.max.copy( box.max );
  2242. return this;
  2243. },
  2244. makeEmpty: function () {
  2245. this.min.x = this.min.y = Infinity;
  2246. this.max.x = this.max.y = - Infinity;
  2247. return this;
  2248. },
  2249. empty: function () {
  2250. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2251. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2252. },
  2253. center: function ( optionalTarget ) {
  2254. var result = optionalTarget || new THREE.Vector2();
  2255. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2256. },
  2257. size: function ( optionalTarget ) {
  2258. var result = optionalTarget || new THREE.Vector2();
  2259. return result.subVectors( this.max, this.min );
  2260. },
  2261. expandByPoint: function ( point ) {
  2262. this.min.min( point );
  2263. this.max.max( point );
  2264. return this;
  2265. },
  2266. expandByVector: function ( vector ) {
  2267. this.min.sub( vector );
  2268. this.max.add( vector );
  2269. return this;
  2270. },
  2271. expandByScalar: function ( scalar ) {
  2272. this.min.addScalar( - scalar );
  2273. this.max.addScalar( scalar );
  2274. return this;
  2275. },
  2276. containsPoint: function ( point ) {
  2277. if ( point.x < this.min.x || point.x > this.max.x ||
  2278. point.y < this.min.y || point.y > this.max.y ) {
  2279. return false;
  2280. }
  2281. return true;
  2282. },
  2283. containsBox: function ( box ) {
  2284. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2285. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2286. return true;
  2287. }
  2288. return false;
  2289. },
  2290. getParameter: function ( point, optionalTarget ) {
  2291. // This can potentially have a divide by zero if the box
  2292. // has a size dimension of 0.
  2293. var result = optionalTarget || new THREE.Vector2();
  2294. return result.set(
  2295. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2296. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2297. );
  2298. },
  2299. intersectsBox: function ( box ) {
  2300. // using 6 splitting planes to rule out intersections.
  2301. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2302. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2303. return false;
  2304. }
  2305. return true;
  2306. },
  2307. clampPoint: function ( point, optionalTarget ) {
  2308. var result = optionalTarget || new THREE.Vector2();
  2309. return result.copy( point ).clamp( this.min, this.max );
  2310. },
  2311. distanceToPoint: function () {
  2312. var v1 = new THREE.Vector2();
  2313. return function ( point ) {
  2314. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2315. return clampedPoint.sub( point ).length();
  2316. };
  2317. }(),
  2318. intersect: function ( box ) {
  2319. this.min.max( box.min );
  2320. this.max.min( box.max );
  2321. return this;
  2322. },
  2323. union: function ( box ) {
  2324. this.min.min( box.min );
  2325. this.max.max( box.max );
  2326. return this;
  2327. },
  2328. translate: function ( offset ) {
  2329. this.min.add( offset );
  2330. this.max.add( offset );
  2331. return this;
  2332. },
  2333. equals: function ( box ) {
  2334. return box.min.equals( this.min ) && box.max.equals( this.max );
  2335. }
  2336. };
  2337. // File:src/math/Box3.js
  2338. /**
  2339. * @author bhouston / http://clara.io
  2340. * @author WestLangley / http://github.com/WestLangley
  2341. */
  2342. THREE.Box3 = function ( min, max ) {
  2343. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2344. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2345. };
  2346. THREE.Box3.prototype = {
  2347. constructor: THREE.Box3,
  2348. set: function ( min, max ) {
  2349. this.min.copy( min );
  2350. this.max.copy( max );
  2351. return this;
  2352. },
  2353. setFromPoints: function ( points ) {
  2354. this.makeEmpty();
  2355. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2356. this.expandByPoint( points[ i ] );
  2357. }
  2358. return this;
  2359. },
  2360. setFromCenterAndSize: function () {
  2361. var v1 = new THREE.Vector3();
  2362. return function ( center, size ) {
  2363. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2364. this.min.copy( center ).sub( halfSize );
  2365. this.max.copy( center ).add( halfSize );
  2366. return this;
  2367. };
  2368. }(),
  2369. setFromObject: function () {
  2370. // Computes the world-axis-aligned bounding box of an object (including its children),
  2371. // accounting for both the object's, and children's, world transforms
  2372. var box;
  2373. return function ( object ) {
  2374. if ( box === undefined ) box = new THREE.Box3();
  2375. var scope = this;
  2376. this.makeEmpty();
  2377. object.updateMatrixWorld( true );
  2378. object.traverse( function ( node ) {
  2379. var geometry = node.geometry;
  2380. if ( geometry !== undefined ) {
  2381. if ( geometry.boundingBox === null ) {
  2382. geometry.computeBoundingBox();
  2383. }
  2384. box.copy( geometry.boundingBox );
  2385. box.applyMatrix4( node.matrixWorld );
  2386. scope.union( box );
  2387. }
  2388. } );
  2389. return this;
  2390. };
  2391. }(),
  2392. clone: function () {
  2393. return new this.constructor().copy( this );
  2394. },
  2395. copy: function ( box ) {
  2396. this.min.copy( box.min );
  2397. this.max.copy( box.max );
  2398. return this;
  2399. },
  2400. makeEmpty: function () {
  2401. this.min.x = this.min.y = this.min.z = Infinity;
  2402. this.max.x = this.max.y = this.max.z = - Infinity;
  2403. return this;
  2404. },
  2405. empty: function () {
  2406. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2407. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2408. },
  2409. center: function ( optionalTarget ) {
  2410. var result = optionalTarget || new THREE.Vector3();
  2411. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2412. },
  2413. size: function ( optionalTarget ) {
  2414. var result = optionalTarget || new THREE.Vector3();
  2415. return result.subVectors( this.max, this.min );
  2416. },
  2417. expandByPoint: function ( point ) {
  2418. this.min.min( point );
  2419. this.max.max( point );
  2420. return this;
  2421. },
  2422. expandByVector: function ( vector ) {
  2423. this.min.sub( vector );
  2424. this.max.add( vector );
  2425. return this;
  2426. },
  2427. expandByScalar: function ( scalar ) {
  2428. this.min.addScalar( - scalar );
  2429. this.max.addScalar( scalar );
  2430. return this;
  2431. },
  2432. containsPoint: function ( point ) {
  2433. if ( point.x < this.min.x || point.x > this.max.x ||
  2434. point.y < this.min.y || point.y > this.max.y ||
  2435. point.z < this.min.z || point.z > this.max.z ) {
  2436. return false;
  2437. }
  2438. return true;
  2439. },
  2440. containsBox: function ( box ) {
  2441. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2442. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2443. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2444. return true;
  2445. }
  2446. return false;
  2447. },
  2448. getParameter: function ( point, optionalTarget ) {
  2449. // This can potentially have a divide by zero if the box
  2450. // has a size dimension of 0.
  2451. var result = optionalTarget || new THREE.Vector3();
  2452. return result.set(
  2453. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2454. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2455. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2456. );
  2457. },
  2458. intersectsBox: function ( box ) {
  2459. // using 6 splitting planes to rule out intersections.
  2460. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2461. box.max.y < this.min.y || box.min.y > this.max.y ||
  2462. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2463. return false;
  2464. }
  2465. return true;
  2466. },
  2467. intersectsSphere: ( function () {
  2468. var closestPoint;
  2469. return function intersectsSphere( sphere ) {
  2470. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2471. // Find the point on the AABB closest to the sphere center.
  2472. this.clampPoint( sphere.center, closestPoint );
  2473. // If that point is inside the sphere, the AABB and sphere intersect.
  2474. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2475. };
  2476. } )(),
  2477. intersectsPlane: function ( plane ) {
  2478. // We compute the minimum and maximum dot product values. If those values
  2479. // are on the same side (back or front) of the plane, then there is no intersection.
  2480. var min, max;
  2481. if( plane.normal.x > 0 ) {
  2482. min = plane.normal.x * this.min.x;
  2483. max = plane.normal.x * this.max.x;
  2484. } else {
  2485. min = plane.normal.x * this.max.x;
  2486. max = plane.normal.x * this.min.x;
  2487. }
  2488. if( plane.normal.y > 0 ) {
  2489. min += plane.normal.y * this.min.y;
  2490. max += plane.normal.y * this.max.y;
  2491. } else {
  2492. min += plane.normal.y * this.max.y;
  2493. max += plane.normal.y * this.min.y;
  2494. }
  2495. if( plane.normal.z > 0 ) {
  2496. min += plane.normal.z * this.min.z;
  2497. max += plane.normal.z * this.max.z;
  2498. } else {
  2499. min += plane.normal.z * this.max.z;
  2500. max += plane.normal.z * this.min.z;
  2501. }
  2502. return ( min <= plane.constant && max >= plane.constant );
  2503. },
  2504. clampPoint: function ( point, optionalTarget ) {
  2505. var result = optionalTarget || new THREE.Vector3();
  2506. return result.copy( point ).clamp( this.min, this.max );
  2507. },
  2508. distanceToPoint: function () {
  2509. var v1 = new THREE.Vector3();
  2510. return function ( point ) {
  2511. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2512. return clampedPoint.sub( point ).length();
  2513. };
  2514. }(),
  2515. getBoundingSphere: function () {
  2516. var v1 = new THREE.Vector3();
  2517. return function ( optionalTarget ) {
  2518. var result = optionalTarget || new THREE.Sphere();
  2519. result.center = this.center();
  2520. result.radius = this.size( v1 ).length() * 0.5;
  2521. return result;
  2522. };
  2523. }(),
  2524. intersect: function ( box ) {
  2525. this.min.max( box.min );
  2526. this.max.min( box.max );
  2527. return this;
  2528. },
  2529. union: function ( box ) {
  2530. this.min.min( box.min );
  2531. this.max.max( box.max );
  2532. return this;
  2533. },
  2534. applyMatrix4: function () {
  2535. var points = [
  2536. new THREE.Vector3(),
  2537. new THREE.Vector3(),
  2538. new THREE.Vector3(),
  2539. new THREE.Vector3(),
  2540. new THREE.Vector3(),
  2541. new THREE.Vector3(),
  2542. new THREE.Vector3(),
  2543. new THREE.Vector3()
  2544. ];
  2545. return function ( matrix ) {
  2546. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2547. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2548. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2549. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2550. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2551. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2552. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2553. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2554. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2555. this.makeEmpty();
  2556. this.setFromPoints( points );
  2557. return this;
  2558. };
  2559. }(),
  2560. translate: function ( offset ) {
  2561. this.min.add( offset );
  2562. this.max.add( offset );
  2563. return this;
  2564. },
  2565. equals: function ( box ) {
  2566. return box.min.equals( this.min ) && box.max.equals( this.max );
  2567. }
  2568. };
  2569. // File:src/math/Matrix3.js
  2570. /**
  2571. * @author alteredq / http://alteredqualia.com/
  2572. * @author WestLangley / http://github.com/WestLangley
  2573. * @author bhouston / http://clara.io
  2574. */
  2575. THREE.Matrix3 = function () {
  2576. this.elements = new Float32Array( [
  2577. 1, 0, 0,
  2578. 0, 1, 0,
  2579. 0, 0, 1
  2580. ] );
  2581. if ( arguments.length > 0 ) {
  2582. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2583. }
  2584. };
  2585. THREE.Matrix3.prototype = {
  2586. constructor: THREE.Matrix3,
  2587. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2588. var te = this.elements;
  2589. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2590. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2591. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2592. return this;
  2593. },
  2594. identity: function () {
  2595. this.set(
  2596. 1, 0, 0,
  2597. 0, 1, 0,
  2598. 0, 0, 1
  2599. );
  2600. return this;
  2601. },
  2602. clone: function () {
  2603. return new this.constructor().fromArray( this.elements );
  2604. },
  2605. copy: function ( m ) {
  2606. var me = m.elements;
  2607. this.set(
  2608. me[ 0 ], me[ 3 ], me[ 6 ],
  2609. me[ 1 ], me[ 4 ], me[ 7 ],
  2610. me[ 2 ], me[ 5 ], me[ 8 ]
  2611. );
  2612. return this;
  2613. },
  2614. applyToVector3Array: function () {
  2615. var v1;
  2616. return function ( array, offset, length ) {
  2617. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2618. if ( offset === undefined ) offset = 0;
  2619. if ( length === undefined ) length = array.length;
  2620. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2621. v1.fromArray( array, j );
  2622. v1.applyMatrix3( this );
  2623. v1.toArray( array, j );
  2624. }
  2625. return array;
  2626. };
  2627. }(),
  2628. applyToBuffer: function () {
  2629. var v1;
  2630. return function applyToBuffer( buffer, offset, length ) {
  2631. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2632. if ( offset === undefined ) offset = 0;
  2633. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2634. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2635. v1.x = buffer.getX( j );
  2636. v1.y = buffer.getY( j );
  2637. v1.z = buffer.getZ( j );
  2638. v1.applyMatrix3( this );
  2639. buffer.setXYZ( v1.x, v1.y, v1.z );
  2640. }
  2641. return buffer;
  2642. };
  2643. }(),
  2644. multiplyScalar: function ( s ) {
  2645. var te = this.elements;
  2646. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2647. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2648. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2649. return this;
  2650. },
  2651. determinant: function () {
  2652. var te = this.elements;
  2653. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2654. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2655. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2656. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2657. },
  2658. getInverse: function ( matrix, throwOnInvertible ) {
  2659. // input: THREE.Matrix4
  2660. // ( based on http://code.google.com/p/webgl-mjs/ )
  2661. var me = matrix.elements;
  2662. var te = this.elements;
  2663. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2664. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2665. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2666. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2667. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2668. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2669. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2670. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2671. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2672. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2673. // no inverse
  2674. if ( det === 0 ) {
  2675. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2676. if ( throwOnInvertible || false ) {
  2677. throw new Error( msg );
  2678. } else {
  2679. console.warn( msg );
  2680. }
  2681. this.identity();
  2682. return this;
  2683. }
  2684. this.multiplyScalar( 1.0 / det );
  2685. return this;
  2686. },
  2687. transpose: function () {
  2688. var tmp, m = this.elements;
  2689. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2690. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2691. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2692. return this;
  2693. },
  2694. flattenToArrayOffset: function ( array, offset ) {
  2695. var te = this.elements;
  2696. array[ offset ] = te[ 0 ];
  2697. array[ offset + 1 ] = te[ 1 ];
  2698. array[ offset + 2 ] = te[ 2 ];
  2699. array[ offset + 3 ] = te[ 3 ];
  2700. array[ offset + 4 ] = te[ 4 ];
  2701. array[ offset + 5 ] = te[ 5 ];
  2702. array[ offset + 6 ] = te[ 6 ];
  2703. array[ offset + 7 ] = te[ 7 ];
  2704. array[ offset + 8 ] = te[ 8 ];
  2705. return array;
  2706. },
  2707. getNormalMatrix: function ( m ) {
  2708. // input: THREE.Matrix4
  2709. this.getInverse( m ).transpose();
  2710. return this;
  2711. },
  2712. transposeIntoArray: function ( r ) {
  2713. var m = this.elements;
  2714. r[ 0 ] = m[ 0 ];
  2715. r[ 1 ] = m[ 3 ];
  2716. r[ 2 ] = m[ 6 ];
  2717. r[ 3 ] = m[ 1 ];
  2718. r[ 4 ] = m[ 4 ];
  2719. r[ 5 ] = m[ 7 ];
  2720. r[ 6 ] = m[ 2 ];
  2721. r[ 7 ] = m[ 5 ];
  2722. r[ 8 ] = m[ 8 ];
  2723. return this;
  2724. },
  2725. fromArray: function ( array ) {
  2726. this.elements.set( array );
  2727. return this;
  2728. },
  2729. toArray: function () {
  2730. var te = this.elements;
  2731. return [
  2732. te[ 0 ], te[ 1 ], te[ 2 ],
  2733. te[ 3 ], te[ 4 ], te[ 5 ],
  2734. te[ 6 ], te[ 7 ], te[ 8 ]
  2735. ];
  2736. }
  2737. };
  2738. // File:src/math/Matrix4.js
  2739. /**
  2740. * @author mrdoob / http://mrdoob.com/
  2741. * @author supereggbert / http://www.paulbrunt.co.uk/
  2742. * @author philogb / http://blog.thejit.org/
  2743. * @author jordi_ros / http://plattsoft.com
  2744. * @author D1plo1d / http://github.com/D1plo1d
  2745. * @author alteredq / http://alteredqualia.com/
  2746. * @author mikael emtinger / http://gomo.se/
  2747. * @author timknip / http://www.floorplanner.com/
  2748. * @author bhouston / http://clara.io
  2749. * @author WestLangley / http://github.com/WestLangley
  2750. */
  2751. THREE.Matrix4 = function () {
  2752. this.elements = new Float32Array( [
  2753. 1, 0, 0, 0,
  2754. 0, 1, 0, 0,
  2755. 0, 0, 1, 0,
  2756. 0, 0, 0, 1
  2757. ] );
  2758. if ( arguments.length > 0 ) {
  2759. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2760. }
  2761. };
  2762. THREE.Matrix4.prototype = {
  2763. constructor: THREE.Matrix4,
  2764. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2765. var te = this.elements;
  2766. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2767. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2768. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2769. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2770. return this;
  2771. },
  2772. identity: function () {
  2773. this.set(
  2774. 1, 0, 0, 0,
  2775. 0, 1, 0, 0,
  2776. 0, 0, 1, 0,
  2777. 0, 0, 0, 1
  2778. );
  2779. return this;
  2780. },
  2781. clone: function () {
  2782. return new THREE.Matrix4().fromArray( this.elements );
  2783. },
  2784. copy: function ( m ) {
  2785. this.elements.set( m.elements );
  2786. return this;
  2787. },
  2788. copyPosition: function ( m ) {
  2789. var te = this.elements;
  2790. var me = m.elements;
  2791. te[ 12 ] = me[ 12 ];
  2792. te[ 13 ] = me[ 13 ];
  2793. te[ 14 ] = me[ 14 ];
  2794. return this;
  2795. },
  2796. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2797. var te = this.elements;
  2798. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2799. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2800. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2801. return this;
  2802. },
  2803. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2804. this.set(
  2805. xAxis.x, yAxis.x, zAxis.x, 0,
  2806. xAxis.y, yAxis.y, zAxis.y, 0,
  2807. xAxis.z, yAxis.z, zAxis.z, 0,
  2808. 0, 0, 0, 1
  2809. );
  2810. return this;
  2811. },
  2812. extractRotation: function () {
  2813. var v1;
  2814. return function ( m ) {
  2815. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2816. var te = this.elements;
  2817. var me = m.elements;
  2818. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2819. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2820. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2821. te[ 0 ] = me[ 0 ] * scaleX;
  2822. te[ 1 ] = me[ 1 ] * scaleX;
  2823. te[ 2 ] = me[ 2 ] * scaleX;
  2824. te[ 4 ] = me[ 4 ] * scaleY;
  2825. te[ 5 ] = me[ 5 ] * scaleY;
  2826. te[ 6 ] = me[ 6 ] * scaleY;
  2827. te[ 8 ] = me[ 8 ] * scaleZ;
  2828. te[ 9 ] = me[ 9 ] * scaleZ;
  2829. te[ 10 ] = me[ 10 ] * scaleZ;
  2830. return this;
  2831. };
  2832. }(),
  2833. makeRotationFromEuler: function ( euler ) {
  2834. if ( euler instanceof THREE.Euler === false ) {
  2835. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2836. }
  2837. var te = this.elements;
  2838. var x = euler.x, y = euler.y, z = euler.z;
  2839. var a = Math.cos( x ), b = Math.sin( x );
  2840. var c = Math.cos( y ), d = Math.sin( y );
  2841. var e = Math.cos( z ), f = Math.sin( z );
  2842. if ( euler.order === 'XYZ' ) {
  2843. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2844. te[ 0 ] = c * e;
  2845. te[ 4 ] = - c * f;
  2846. te[ 8 ] = d;
  2847. te[ 1 ] = af + be * d;
  2848. te[ 5 ] = ae - bf * d;
  2849. te[ 9 ] = - b * c;
  2850. te[ 2 ] = bf - ae * d;
  2851. te[ 6 ] = be + af * d;
  2852. te[ 10 ] = a * c;
  2853. } else if ( euler.order === 'YXZ' ) {
  2854. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2855. te[ 0 ] = ce + df * b;
  2856. te[ 4 ] = de * b - cf;
  2857. te[ 8 ] = a * d;
  2858. te[ 1 ] = a * f;
  2859. te[ 5 ] = a * e;
  2860. te[ 9 ] = - b;
  2861. te[ 2 ] = cf * b - de;
  2862. te[ 6 ] = df + ce * b;
  2863. te[ 10 ] = a * c;
  2864. } else if ( euler.order === 'ZXY' ) {
  2865. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2866. te[ 0 ] = ce - df * b;
  2867. te[ 4 ] = - a * f;
  2868. te[ 8 ] = de + cf * b;
  2869. te[ 1 ] = cf + de * b;
  2870. te[ 5 ] = a * e;
  2871. te[ 9 ] = df - ce * b;
  2872. te[ 2 ] = - a * d;
  2873. te[ 6 ] = b;
  2874. te[ 10 ] = a * c;
  2875. } else if ( euler.order === 'ZYX' ) {
  2876. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2877. te[ 0 ] = c * e;
  2878. te[ 4 ] = be * d - af;
  2879. te[ 8 ] = ae * d + bf;
  2880. te[ 1 ] = c * f;
  2881. te[ 5 ] = bf * d + ae;
  2882. te[ 9 ] = af * d - be;
  2883. te[ 2 ] = - d;
  2884. te[ 6 ] = b * c;
  2885. te[ 10 ] = a * c;
  2886. } else if ( euler.order === 'YZX' ) {
  2887. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2888. te[ 0 ] = c * e;
  2889. te[ 4 ] = bd - ac * f;
  2890. te[ 8 ] = bc * f + ad;
  2891. te[ 1 ] = f;
  2892. te[ 5 ] = a * e;
  2893. te[ 9 ] = - b * e;
  2894. te[ 2 ] = - d * e;
  2895. te[ 6 ] = ad * f + bc;
  2896. te[ 10 ] = ac - bd * f;
  2897. } else if ( euler.order === 'XZY' ) {
  2898. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2899. te[ 0 ] = c * e;
  2900. te[ 4 ] = - f;
  2901. te[ 8 ] = d * e;
  2902. te[ 1 ] = ac * f + bd;
  2903. te[ 5 ] = a * e;
  2904. te[ 9 ] = ad * f - bc;
  2905. te[ 2 ] = bc * f - ad;
  2906. te[ 6 ] = b * e;
  2907. te[ 10 ] = bd * f + ac;
  2908. }
  2909. // last column
  2910. te[ 3 ] = 0;
  2911. te[ 7 ] = 0;
  2912. te[ 11 ] = 0;
  2913. // bottom row
  2914. te[ 12 ] = 0;
  2915. te[ 13 ] = 0;
  2916. te[ 14 ] = 0;
  2917. te[ 15 ] = 1;
  2918. return this;
  2919. },
  2920. makeRotationFromQuaternion: function ( q ) {
  2921. var te = this.elements;
  2922. var x = q.x, y = q.y, z = q.z, w = q.w;
  2923. var x2 = x + x, y2 = y + y, z2 = z + z;
  2924. var xx = x * x2, xy = x * y2, xz = x * z2;
  2925. var yy = y * y2, yz = y * z2, zz = z * z2;
  2926. var wx = w * x2, wy = w * y2, wz = w * z2;
  2927. te[ 0 ] = 1 - ( yy + zz );
  2928. te[ 4 ] = xy - wz;
  2929. te[ 8 ] = xz + wy;
  2930. te[ 1 ] = xy + wz;
  2931. te[ 5 ] = 1 - ( xx + zz );
  2932. te[ 9 ] = yz - wx;
  2933. te[ 2 ] = xz - wy;
  2934. te[ 6 ] = yz + wx;
  2935. te[ 10 ] = 1 - ( xx + yy );
  2936. // last column
  2937. te[ 3 ] = 0;
  2938. te[ 7 ] = 0;
  2939. te[ 11 ] = 0;
  2940. // bottom row
  2941. te[ 12 ] = 0;
  2942. te[ 13 ] = 0;
  2943. te[ 14 ] = 0;
  2944. te[ 15 ] = 1;
  2945. return this;
  2946. },
  2947. lookAt: function () {
  2948. var x, y, z;
  2949. return function ( eye, target, up ) {
  2950. if ( x === undefined ) x = new THREE.Vector3();
  2951. if ( y === undefined ) y = new THREE.Vector3();
  2952. if ( z === undefined ) z = new THREE.Vector3();
  2953. var te = this.elements;
  2954. z.subVectors( eye, target ).normalize();
  2955. if ( z.lengthSq() === 0 ) {
  2956. z.z = 1;
  2957. }
  2958. x.crossVectors( up, z ).normalize();
  2959. if ( x.lengthSq() === 0 ) {
  2960. z.x += 0.0001;
  2961. x.crossVectors( up, z ).normalize();
  2962. }
  2963. y.crossVectors( z, x );
  2964. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2965. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2966. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2967. return this;
  2968. };
  2969. }(),
  2970. multiply: function ( m, n ) {
  2971. if ( n !== undefined ) {
  2972. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2973. return this.multiplyMatrices( m, n );
  2974. }
  2975. return this.multiplyMatrices( this, m );
  2976. },
  2977. multiplyMatrices: function ( a, b ) {
  2978. var ae = a.elements;
  2979. var be = b.elements;
  2980. var te = this.elements;
  2981. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2982. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2983. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2984. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2985. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2986. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2987. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2988. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2989. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2990. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2991. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2992. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2993. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2994. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2995. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2996. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2997. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2998. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2999. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3000. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3001. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3002. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3003. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3004. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3005. return this;
  3006. },
  3007. multiplyToArray: function ( a, b, r ) {
  3008. var te = this.elements;
  3009. this.multiplyMatrices( a, b );
  3010. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3011. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3012. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3013. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3014. return this;
  3015. },
  3016. multiplyScalar: function ( s ) {
  3017. var te = this.elements;
  3018. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3019. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3020. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3021. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3022. return this;
  3023. },
  3024. applyToVector3Array: function () {
  3025. var v1;
  3026. return function ( array, offset, length ) {
  3027. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3028. if ( offset === undefined ) offset = 0;
  3029. if ( length === undefined ) length = array.length;
  3030. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3031. v1.fromArray( array, j );
  3032. v1.applyMatrix4( this );
  3033. v1.toArray( array, j );
  3034. }
  3035. return array;
  3036. };
  3037. }(),
  3038. applyToBuffer: function () {
  3039. var v1;
  3040. return function applyToBuffer( buffer, offset, length ) {
  3041. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3042. if ( offset === undefined ) offset = 0;
  3043. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3044. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3045. v1.x = buffer.getX( j );
  3046. v1.y = buffer.getY( j );
  3047. v1.z = buffer.getZ( j );
  3048. v1.applyMatrix4( this );
  3049. buffer.setXYZ( v1.x, v1.y, v1.z );
  3050. }
  3051. return buffer;
  3052. };
  3053. }(),
  3054. determinant: function () {
  3055. var te = this.elements;
  3056. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3057. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3058. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3059. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3060. //TODO: make this more efficient
  3061. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3062. return (
  3063. n41 * (
  3064. + n14 * n23 * n32
  3065. - n13 * n24 * n32
  3066. - n14 * n22 * n33
  3067. + n12 * n24 * n33
  3068. + n13 * n22 * n34
  3069. - n12 * n23 * n34
  3070. ) +
  3071. n42 * (
  3072. + n11 * n23 * n34
  3073. - n11 * n24 * n33
  3074. + n14 * n21 * n33
  3075. - n13 * n21 * n34
  3076. + n13 * n24 * n31
  3077. - n14 * n23 * n31
  3078. ) +
  3079. n43 * (
  3080. + n11 * n24 * n32
  3081. - n11 * n22 * n34
  3082. - n14 * n21 * n32
  3083. + n12 * n21 * n34
  3084. + n14 * n22 * n31
  3085. - n12 * n24 * n31
  3086. ) +
  3087. n44 * (
  3088. - n13 * n22 * n31
  3089. - n11 * n23 * n32
  3090. + n11 * n22 * n33
  3091. + n13 * n21 * n32
  3092. - n12 * n21 * n33
  3093. + n12 * n23 * n31
  3094. )
  3095. );
  3096. },
  3097. transpose: function () {
  3098. var te = this.elements;
  3099. var tmp;
  3100. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3101. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3102. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3103. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3104. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3105. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3106. return this;
  3107. },
  3108. flattenToArrayOffset: function ( array, offset ) {
  3109. var te = this.elements;
  3110. array[ offset ] = te[ 0 ];
  3111. array[ offset + 1 ] = te[ 1 ];
  3112. array[ offset + 2 ] = te[ 2 ];
  3113. array[ offset + 3 ] = te[ 3 ];
  3114. array[ offset + 4 ] = te[ 4 ];
  3115. array[ offset + 5 ] = te[ 5 ];
  3116. array[ offset + 6 ] = te[ 6 ];
  3117. array[ offset + 7 ] = te[ 7 ];
  3118. array[ offset + 8 ] = te[ 8 ];
  3119. array[ offset + 9 ] = te[ 9 ];
  3120. array[ offset + 10 ] = te[ 10 ];
  3121. array[ offset + 11 ] = te[ 11 ];
  3122. array[ offset + 12 ] = te[ 12 ];
  3123. array[ offset + 13 ] = te[ 13 ];
  3124. array[ offset + 14 ] = te[ 14 ];
  3125. array[ offset + 15 ] = te[ 15 ];
  3126. return array;
  3127. },
  3128. getPosition: function () {
  3129. var v1;
  3130. return function () {
  3131. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3132. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3133. var te = this.elements;
  3134. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3135. };
  3136. }(),
  3137. setPosition: function ( v ) {
  3138. var te = this.elements;
  3139. te[ 12 ] = v.x;
  3140. te[ 13 ] = v.y;
  3141. te[ 14 ] = v.z;
  3142. return this;
  3143. },
  3144. getInverse: function ( m, throwOnInvertible ) {
  3145. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3146. var te = this.elements;
  3147. var me = m.elements;
  3148. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3149. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3150. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3151. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3152. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3153. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3154. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3155. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3156. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3157. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3158. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3159. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3160. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3161. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3162. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3163. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3164. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3165. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3166. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3167. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3168. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3169. if ( det === 0 ) {
  3170. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3171. if ( throwOnInvertible || false ) {
  3172. throw new Error( msg );
  3173. } else {
  3174. console.warn( msg );
  3175. }
  3176. this.identity();
  3177. return this;
  3178. }
  3179. this.multiplyScalar( 1 / det );
  3180. return this;
  3181. },
  3182. scale: function ( v ) {
  3183. var te = this.elements;
  3184. var x = v.x, y = v.y, z = v.z;
  3185. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3186. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3187. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3188. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3189. return this;
  3190. },
  3191. getMaxScaleOnAxis: function () {
  3192. var te = this.elements;
  3193. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3194. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3195. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3196. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3197. },
  3198. makeTranslation: function ( x, y, z ) {
  3199. this.set(
  3200. 1, 0, 0, x,
  3201. 0, 1, 0, y,
  3202. 0, 0, 1, z,
  3203. 0, 0, 0, 1
  3204. );
  3205. return this;
  3206. },
  3207. makeRotationX: function ( theta ) {
  3208. var c = Math.cos( theta ), s = Math.sin( theta );
  3209. this.set(
  3210. 1, 0, 0, 0,
  3211. 0, c, - s, 0,
  3212. 0, s, c, 0,
  3213. 0, 0, 0, 1
  3214. );
  3215. return this;
  3216. },
  3217. makeRotationY: function ( theta ) {
  3218. var c = Math.cos( theta ), s = Math.sin( theta );
  3219. this.set(
  3220. c, 0, s, 0,
  3221. 0, 1, 0, 0,
  3222. - s, 0, c, 0,
  3223. 0, 0, 0, 1
  3224. );
  3225. return this;
  3226. },
  3227. makeRotationZ: function ( theta ) {
  3228. var c = Math.cos( theta ), s = Math.sin( theta );
  3229. this.set(
  3230. c, - s, 0, 0,
  3231. s, c, 0, 0,
  3232. 0, 0, 1, 0,
  3233. 0, 0, 0, 1
  3234. );
  3235. return this;
  3236. },
  3237. makeRotationAxis: function ( axis, angle ) {
  3238. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3239. var c = Math.cos( angle );
  3240. var s = Math.sin( angle );
  3241. var t = 1 - c;
  3242. var x = axis.x, y = axis.y, z = axis.z;
  3243. var tx = t * x, ty = t * y;
  3244. this.set(
  3245. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3246. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3247. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3248. 0, 0, 0, 1
  3249. );
  3250. return this;
  3251. },
  3252. makeScale: function ( x, y, z ) {
  3253. this.set(
  3254. x, 0, 0, 0,
  3255. 0, y, 0, 0,
  3256. 0, 0, z, 0,
  3257. 0, 0, 0, 1
  3258. );
  3259. return this;
  3260. },
  3261. compose: function ( position, quaternion, scale ) {
  3262. this.makeRotationFromQuaternion( quaternion );
  3263. this.scale( scale );
  3264. this.setPosition( position );
  3265. return this;
  3266. },
  3267. decompose: function () {
  3268. var vector, matrix;
  3269. return function ( position, quaternion, scale ) {
  3270. if ( vector === undefined ) vector = new THREE.Vector3();
  3271. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3272. var te = this.elements;
  3273. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3274. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3275. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3276. // if determine is negative, we need to invert one scale
  3277. var det = this.determinant();
  3278. if ( det < 0 ) {
  3279. sx = - sx;
  3280. }
  3281. position.x = te[ 12 ];
  3282. position.y = te[ 13 ];
  3283. position.z = te[ 14 ];
  3284. // scale the rotation part
  3285. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3286. var invSX = 1 / sx;
  3287. var invSY = 1 / sy;
  3288. var invSZ = 1 / sz;
  3289. matrix.elements[ 0 ] *= invSX;
  3290. matrix.elements[ 1 ] *= invSX;
  3291. matrix.elements[ 2 ] *= invSX;
  3292. matrix.elements[ 4 ] *= invSY;
  3293. matrix.elements[ 5 ] *= invSY;
  3294. matrix.elements[ 6 ] *= invSY;
  3295. matrix.elements[ 8 ] *= invSZ;
  3296. matrix.elements[ 9 ] *= invSZ;
  3297. matrix.elements[ 10 ] *= invSZ;
  3298. quaternion.setFromRotationMatrix( matrix );
  3299. scale.x = sx;
  3300. scale.y = sy;
  3301. scale.z = sz;
  3302. return this;
  3303. };
  3304. }(),
  3305. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3306. var te = this.elements;
  3307. var x = 2 * near / ( right - left );
  3308. var y = 2 * near / ( top - bottom );
  3309. var a = ( right + left ) / ( right - left );
  3310. var b = ( top + bottom ) / ( top - bottom );
  3311. var c = - ( far + near ) / ( far - near );
  3312. var d = - 2 * far * near / ( far - near );
  3313. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3314. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3315. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3316. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3317. return this;
  3318. },
  3319. makePerspective: function ( fov, aspect, near, far ) {
  3320. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3321. var ymin = - ymax;
  3322. var xmin = ymin * aspect;
  3323. var xmax = ymax * aspect;
  3324. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3325. },
  3326. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3327. var te = this.elements;
  3328. var w = right - left;
  3329. var h = top - bottom;
  3330. var p = far - near;
  3331. var x = ( right + left ) / w;
  3332. var y = ( top + bottom ) / h;
  3333. var z = ( far + near ) / p;
  3334. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3335. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3336. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3337. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3338. return this;
  3339. },
  3340. equals: function ( matrix ) {
  3341. var te = this.elements;
  3342. var me = matrix.elements;
  3343. for ( var i = 0; i < 16; i ++ ) {
  3344. if ( te[ i ] !== me[ i ] ) return false;
  3345. }
  3346. return true;
  3347. },
  3348. fromArray: function ( array ) {
  3349. this.elements.set( array );
  3350. return this;
  3351. },
  3352. toArray: function () {
  3353. var te = this.elements;
  3354. return [
  3355. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3356. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3357. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3358. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3359. ];
  3360. }
  3361. };
  3362. // File:src/math/Ray.js
  3363. /**
  3364. * @author bhouston / http://clara.io
  3365. */
  3366. THREE.Ray = function ( origin, direction ) {
  3367. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3368. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3369. };
  3370. THREE.Ray.prototype = {
  3371. constructor: THREE.Ray,
  3372. set: function ( origin, direction ) {
  3373. this.origin.copy( origin );
  3374. this.direction.copy( direction );
  3375. return this;
  3376. },
  3377. clone: function () {
  3378. return new this.constructor().copy( this );
  3379. },
  3380. copy: function ( ray ) {
  3381. this.origin.copy( ray.origin );
  3382. this.direction.copy( ray.direction );
  3383. return this;
  3384. },
  3385. at: function ( t, optionalTarget ) {
  3386. var result = optionalTarget || new THREE.Vector3();
  3387. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3388. },
  3389. recast: function () {
  3390. var v1 = new THREE.Vector3();
  3391. return function ( t ) {
  3392. this.origin.copy( this.at( t, v1 ) );
  3393. return this;
  3394. };
  3395. }(),
  3396. closestPointToPoint: function ( point, optionalTarget ) {
  3397. var result = optionalTarget || new THREE.Vector3();
  3398. result.subVectors( point, this.origin );
  3399. var directionDistance = result.dot( this.direction );
  3400. if ( directionDistance < 0 ) {
  3401. return result.copy( this.origin );
  3402. }
  3403. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3404. },
  3405. distanceToPoint: function ( point ) {
  3406. return Math.sqrt( this.distanceSqToPoint( point ) );
  3407. },
  3408. distanceSqToPoint: function () {
  3409. var v1 = new THREE.Vector3();
  3410. return function ( point ) {
  3411. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3412. // point behind the ray
  3413. if ( directionDistance < 0 ) {
  3414. return this.origin.distanceToSquared( point );
  3415. }
  3416. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3417. return v1.distanceToSquared( point );
  3418. };
  3419. }(),
  3420. distanceSqToSegment: function () {
  3421. var segCenter = new THREE.Vector3();
  3422. var segDir = new THREE.Vector3();
  3423. var diff = new THREE.Vector3();
  3424. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3425. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3426. // It returns the min distance between the ray and the segment
  3427. // defined by v0 and v1
  3428. // It can also set two optional targets :
  3429. // - The closest point on the ray
  3430. // - The closest point on the segment
  3431. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3432. segDir.copy( v1 ).sub( v0 ).normalize();
  3433. diff.copy( this.origin ).sub( segCenter );
  3434. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3435. var a01 = - this.direction.dot( segDir );
  3436. var b0 = diff.dot( this.direction );
  3437. var b1 = - diff.dot( segDir );
  3438. var c = diff.lengthSq();
  3439. var det = Math.abs( 1 - a01 * a01 );
  3440. var s0, s1, sqrDist, extDet;
  3441. if ( det > 0 ) {
  3442. // The ray and segment are not parallel.
  3443. s0 = a01 * b1 - b0;
  3444. s1 = a01 * b0 - b1;
  3445. extDet = segExtent * det;
  3446. if ( s0 >= 0 ) {
  3447. if ( s1 >= - extDet ) {
  3448. if ( s1 <= extDet ) {
  3449. // region 0
  3450. // Minimum at interior points of ray and segment.
  3451. var invDet = 1 / det;
  3452. s0 *= invDet;
  3453. s1 *= invDet;
  3454. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3455. } else {
  3456. // region 1
  3457. s1 = segExtent;
  3458. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3459. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3460. }
  3461. } else {
  3462. // region 5
  3463. s1 = - segExtent;
  3464. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3465. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3466. }
  3467. } else {
  3468. if ( s1 <= - extDet ) {
  3469. // region 4
  3470. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3471. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3472. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3473. } else if ( s1 <= extDet ) {
  3474. // region 3
  3475. s0 = 0;
  3476. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3477. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3478. } else {
  3479. // region 2
  3480. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3481. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3482. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3483. }
  3484. }
  3485. } else {
  3486. // Ray and segment are parallel.
  3487. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3488. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3489. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3490. }
  3491. if ( optionalPointOnRay ) {
  3492. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3493. }
  3494. if ( optionalPointOnSegment ) {
  3495. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3496. }
  3497. return sqrDist;
  3498. };
  3499. }(),
  3500. intersectSphere: function () {
  3501. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3502. var v1 = new THREE.Vector3();
  3503. return function ( sphere, optionalTarget ) {
  3504. v1.subVectors( sphere.center, this.origin );
  3505. var tca = v1.dot( this.direction );
  3506. var d2 = v1.dot( v1 ) - tca * tca;
  3507. var radius2 = sphere.radius * sphere.radius;
  3508. if ( d2 > radius2 ) return null;
  3509. var thc = Math.sqrt( radius2 - d2 );
  3510. // t0 = first intersect point - entrance on front of sphere
  3511. var t0 = tca - thc;
  3512. // t1 = second intersect point - exit point on back of sphere
  3513. var t1 = tca + thc;
  3514. // test to see if both t0 and t1 are behind the ray - if so, return null
  3515. if ( t0 < 0 && t1 < 0 ) return null;
  3516. // test to see if t0 is behind the ray:
  3517. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3518. // in order to always return an intersect point that is in front of the ray.
  3519. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3520. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3521. return this.at( t0, optionalTarget );
  3522. }
  3523. }(),
  3524. intersectsSphere: function ( sphere ) {
  3525. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3526. },
  3527. distanceToPlane: function ( plane ) {
  3528. var denominator = plane.normal.dot( this.direction );
  3529. if ( denominator === 0 ) {
  3530. // line is coplanar, return origin
  3531. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3532. return 0;
  3533. }
  3534. // Null is preferable to undefined since undefined means.... it is undefined
  3535. return null;
  3536. }
  3537. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3538. // Return if the ray never intersects the plane
  3539. return t >= 0 ? t : null;
  3540. },
  3541. intersectPlane: function ( plane, optionalTarget ) {
  3542. var t = this.distanceToPlane( plane );
  3543. if ( t === null ) {
  3544. return null;
  3545. }
  3546. return this.at( t, optionalTarget );
  3547. },
  3548. intersectsPlane: function ( plane ) {
  3549. // check if the ray lies on the plane first
  3550. var distToPoint = plane.distanceToPoint( this.origin );
  3551. if ( distToPoint === 0 ) {
  3552. return true;
  3553. }
  3554. var denominator = plane.normal.dot( this.direction );
  3555. if ( denominator * distToPoint < 0 ) {
  3556. return true;
  3557. }
  3558. // ray origin is behind the plane (and is pointing behind it)
  3559. return false;
  3560. },
  3561. intersectBox: function ( box, optionalTarget ) {
  3562. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3563. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3564. var invdirx = 1 / this.direction.x,
  3565. invdiry = 1 / this.direction.y,
  3566. invdirz = 1 / this.direction.z;
  3567. var origin = this.origin;
  3568. if ( invdirx >= 0 ) {
  3569. tmin = ( box.min.x - origin.x ) * invdirx;
  3570. tmax = ( box.max.x - origin.x ) * invdirx;
  3571. } else {
  3572. tmin = ( box.max.x - origin.x ) * invdirx;
  3573. tmax = ( box.min.x - origin.x ) * invdirx;
  3574. }
  3575. if ( invdiry >= 0 ) {
  3576. tymin = ( box.min.y - origin.y ) * invdiry;
  3577. tymax = ( box.max.y - origin.y ) * invdiry;
  3578. } else {
  3579. tymin = ( box.max.y - origin.y ) * invdiry;
  3580. tymax = ( box.min.y - origin.y ) * invdiry;
  3581. }
  3582. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3583. // These lines also handle the case where tmin or tmax is NaN
  3584. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3585. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3586. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3587. if ( invdirz >= 0 ) {
  3588. tzmin = ( box.min.z - origin.z ) * invdirz;
  3589. tzmax = ( box.max.z - origin.z ) * invdirz;
  3590. } else {
  3591. tzmin = ( box.max.z - origin.z ) * invdirz;
  3592. tzmax = ( box.min.z - origin.z ) * invdirz;
  3593. }
  3594. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3595. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3596. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3597. //return point closest to the ray (positive side)
  3598. if ( tmax < 0 ) return null;
  3599. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3600. },
  3601. intersectsBox: ( function () {
  3602. var v = new THREE.Vector3();
  3603. return function ( box ) {
  3604. return this.intersectBox( box, v ) !== null;
  3605. };
  3606. } )(),
  3607. intersectTriangle: function () {
  3608. // Compute the offset origin, edges, and normal.
  3609. var diff = new THREE.Vector3();
  3610. var edge1 = new THREE.Vector3();
  3611. var edge2 = new THREE.Vector3();
  3612. var normal = new THREE.Vector3();
  3613. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3614. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3615. edge1.subVectors( b, a );
  3616. edge2.subVectors( c, a );
  3617. normal.crossVectors( edge1, edge2 );
  3618. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3619. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3620. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3621. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3622. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3623. var DdN = this.direction.dot( normal );
  3624. var sign;
  3625. if ( DdN > 0 ) {
  3626. if ( backfaceCulling ) return null;
  3627. sign = 1;
  3628. } else if ( DdN < 0 ) {
  3629. sign = - 1;
  3630. DdN = - DdN;
  3631. } else {
  3632. return null;
  3633. }
  3634. diff.subVectors( this.origin, a );
  3635. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3636. // b1 < 0, no intersection
  3637. if ( DdQxE2 < 0 ) {
  3638. return null;
  3639. }
  3640. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3641. // b2 < 0, no intersection
  3642. if ( DdE1xQ < 0 ) {
  3643. return null;
  3644. }
  3645. // b1+b2 > 1, no intersection
  3646. if ( DdQxE2 + DdE1xQ > DdN ) {
  3647. return null;
  3648. }
  3649. // Line intersects triangle, check if ray does.
  3650. var QdN = - sign * diff.dot( normal );
  3651. // t < 0, no intersection
  3652. if ( QdN < 0 ) {
  3653. return null;
  3654. }
  3655. // Ray intersects triangle.
  3656. return this.at( QdN / DdN, optionalTarget );
  3657. };
  3658. }(),
  3659. applyMatrix4: function ( matrix4 ) {
  3660. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3661. this.origin.applyMatrix4( matrix4 );
  3662. this.direction.sub( this.origin );
  3663. this.direction.normalize();
  3664. return this;
  3665. },
  3666. equals: function ( ray ) {
  3667. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3668. }
  3669. };
  3670. // File:src/math/Sphere.js
  3671. /**
  3672. * @author bhouston / http://clara.io
  3673. * @author mrdoob / http://mrdoob.com/
  3674. */
  3675. THREE.Sphere = function ( center, radius ) {
  3676. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3677. this.radius = ( radius !== undefined ) ? radius : 0;
  3678. };
  3679. THREE.Sphere.prototype = {
  3680. constructor: THREE.Sphere,
  3681. set: function ( center, radius ) {
  3682. this.center.copy( center );
  3683. this.radius = radius;
  3684. return this;
  3685. },
  3686. setFromPoints: function () {
  3687. var box = new THREE.Box3();
  3688. return function ( points, optionalCenter ) {
  3689. var center = this.center;
  3690. if ( optionalCenter !== undefined ) {
  3691. center.copy( optionalCenter );
  3692. } else {
  3693. box.setFromPoints( points ).center( center );
  3694. }
  3695. var maxRadiusSq = 0;
  3696. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3697. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3698. }
  3699. this.radius = Math.sqrt( maxRadiusSq );
  3700. return this;
  3701. };
  3702. }(),
  3703. clone: function () {
  3704. return new this.constructor().copy( this );
  3705. },
  3706. copy: function ( sphere ) {
  3707. this.center.copy( sphere.center );
  3708. this.radius = sphere.radius;
  3709. return this;
  3710. },
  3711. empty: function () {
  3712. return ( this.radius <= 0 );
  3713. },
  3714. containsPoint: function ( point ) {
  3715. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3716. },
  3717. distanceToPoint: function ( point ) {
  3718. return ( point.distanceTo( this.center ) - this.radius );
  3719. },
  3720. intersectsSphere: function ( sphere ) {
  3721. var radiusSum = this.radius + sphere.radius;
  3722. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3723. },
  3724. intersectsBox: function ( box ) {
  3725. return box.intersectsSphere( this );
  3726. },
  3727. intersectsPlane: function ( plane ) {
  3728. // We use the following equation to compute the signed distance from
  3729. // the center of the sphere to the plane.
  3730. //
  3731. // distance = q * n - d
  3732. //
  3733. // If this distance is greater than the radius of the sphere,
  3734. // then there is no intersection.
  3735. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3736. },
  3737. clampPoint: function ( point, optionalTarget ) {
  3738. var deltaLengthSq = this.center.distanceToSquared( point );
  3739. var result = optionalTarget || new THREE.Vector3();
  3740. result.copy( point );
  3741. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3742. result.sub( this.center ).normalize();
  3743. result.multiplyScalar( this.radius ).add( this.center );
  3744. }
  3745. return result;
  3746. },
  3747. getBoundingBox: function ( optionalTarget ) {
  3748. var box = optionalTarget || new THREE.Box3();
  3749. box.set( this.center, this.center );
  3750. box.expandByScalar( this.radius );
  3751. return box;
  3752. },
  3753. applyMatrix4: function ( matrix ) {
  3754. this.center.applyMatrix4( matrix );
  3755. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3756. return this;
  3757. },
  3758. translate: function ( offset ) {
  3759. this.center.add( offset );
  3760. return this;
  3761. },
  3762. equals: function ( sphere ) {
  3763. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3764. }
  3765. };
  3766. // File:src/math/Frustum.js
  3767. /**
  3768. * @author mrdoob / http://mrdoob.com/
  3769. * @author alteredq / http://alteredqualia.com/
  3770. * @author bhouston / http://clara.io
  3771. */
  3772. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3773. this.planes = [
  3774. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3775. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3776. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3777. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3778. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3779. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3780. ];
  3781. };
  3782. THREE.Frustum.prototype = {
  3783. constructor: THREE.Frustum,
  3784. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3785. var planes = this.planes;
  3786. planes[ 0 ].copy( p0 );
  3787. planes[ 1 ].copy( p1 );
  3788. planes[ 2 ].copy( p2 );
  3789. planes[ 3 ].copy( p3 );
  3790. planes[ 4 ].copy( p4 );
  3791. planes[ 5 ].copy( p5 );
  3792. return this;
  3793. },
  3794. clone: function () {
  3795. return new this.constructor().copy( this );
  3796. },
  3797. copy: function ( frustum ) {
  3798. var planes = this.planes;
  3799. for ( var i = 0; i < 6; i ++ ) {
  3800. planes[ i ].copy( frustum.planes[ i ] );
  3801. }
  3802. return this;
  3803. },
  3804. setFromMatrix: function ( m ) {
  3805. var planes = this.planes;
  3806. var me = m.elements;
  3807. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3808. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3809. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3810. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3811. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3812. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3813. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3814. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3815. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3816. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3817. return this;
  3818. },
  3819. intersectsObject: function () {
  3820. var sphere = new THREE.Sphere();
  3821. return function ( object ) {
  3822. var geometry = object.geometry;
  3823. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3824. sphere.copy( geometry.boundingSphere );
  3825. sphere.applyMatrix4( object.matrixWorld );
  3826. return this.intersectsSphere( sphere );
  3827. };
  3828. }(),
  3829. intersectsSphere: function ( sphere ) {
  3830. var planes = this.planes;
  3831. var center = sphere.center;
  3832. var negRadius = - sphere.radius;
  3833. for ( var i = 0; i < 6; i ++ ) {
  3834. var distance = planes[ i ].distanceToPoint( center );
  3835. if ( distance < negRadius ) {
  3836. return false;
  3837. }
  3838. }
  3839. return true;
  3840. },
  3841. intersectsBox: function () {
  3842. var p1 = new THREE.Vector3(),
  3843. p2 = new THREE.Vector3();
  3844. return function ( box ) {
  3845. var planes = this.planes;
  3846. for ( var i = 0; i < 6 ; i ++ ) {
  3847. var plane = planes[ i ];
  3848. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3849. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3850. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3851. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3852. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3853. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3854. var d1 = plane.distanceToPoint( p1 );
  3855. var d2 = plane.distanceToPoint( p2 );
  3856. // if both outside plane, no intersection
  3857. if ( d1 < 0 && d2 < 0 ) {
  3858. return false;
  3859. }
  3860. }
  3861. return true;
  3862. };
  3863. }(),
  3864. containsPoint: function ( point ) {
  3865. var planes = this.planes;
  3866. for ( var i = 0; i < 6; i ++ ) {
  3867. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3868. return false;
  3869. }
  3870. }
  3871. return true;
  3872. }
  3873. };
  3874. // File:src/math/Plane.js
  3875. /**
  3876. * @author bhouston / http://clara.io
  3877. */
  3878. THREE.Plane = function ( normal, constant ) {
  3879. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3880. this.constant = ( constant !== undefined ) ? constant : 0;
  3881. };
  3882. THREE.Plane.prototype = {
  3883. constructor: THREE.Plane,
  3884. set: function ( normal, constant ) {
  3885. this.normal.copy( normal );
  3886. this.constant = constant;
  3887. return this;
  3888. },
  3889. setComponents: function ( x, y, z, w ) {
  3890. this.normal.set( x, y, z );
  3891. this.constant = w;
  3892. return this;
  3893. },
  3894. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3895. this.normal.copy( normal );
  3896. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3897. return this;
  3898. },
  3899. setFromCoplanarPoints: function () {
  3900. var v1 = new THREE.Vector3();
  3901. var v2 = new THREE.Vector3();
  3902. return function ( a, b, c ) {
  3903. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3904. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3905. this.setFromNormalAndCoplanarPoint( normal, a );
  3906. return this;
  3907. };
  3908. }(),
  3909. clone: function () {
  3910. return new this.constructor().copy( this );
  3911. },
  3912. copy: function ( plane ) {
  3913. this.normal.copy( plane.normal );
  3914. this.constant = plane.constant;
  3915. return this;
  3916. },
  3917. normalize: function () {
  3918. // Note: will lead to a divide by zero if the plane is invalid.
  3919. var inverseNormalLength = 1.0 / this.normal.length();
  3920. this.normal.multiplyScalar( inverseNormalLength );
  3921. this.constant *= inverseNormalLength;
  3922. return this;
  3923. },
  3924. negate: function () {
  3925. this.constant *= - 1;
  3926. this.normal.negate();
  3927. return this;
  3928. },
  3929. distanceToPoint: function ( point ) {
  3930. return this.normal.dot( point ) + this.constant;
  3931. },
  3932. distanceToSphere: function ( sphere ) {
  3933. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3934. },
  3935. projectPoint: function ( point, optionalTarget ) {
  3936. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3937. },
  3938. orthoPoint: function ( point, optionalTarget ) {
  3939. var perpendicularMagnitude = this.distanceToPoint( point );
  3940. var result = optionalTarget || new THREE.Vector3();
  3941. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3942. },
  3943. intersectLine: function () {
  3944. var v1 = new THREE.Vector3();
  3945. return function ( line, optionalTarget ) {
  3946. var result = optionalTarget || new THREE.Vector3();
  3947. var direction = line.delta( v1 );
  3948. var denominator = this.normal.dot( direction );
  3949. if ( denominator === 0 ) {
  3950. // line is coplanar, return origin
  3951. if ( this.distanceToPoint( line.start ) === 0 ) {
  3952. return result.copy( line.start );
  3953. }
  3954. // Unsure if this is the correct method to handle this case.
  3955. return undefined;
  3956. }
  3957. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3958. if ( t < 0 || t > 1 ) {
  3959. return undefined;
  3960. }
  3961. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3962. };
  3963. }(),
  3964. intersectsLine: function ( line ) {
  3965. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3966. var startSign = this.distanceToPoint( line.start );
  3967. var endSign = this.distanceToPoint( line.end );
  3968. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3969. },
  3970. intersectsBox: function ( box ) {
  3971. return box.intersectsPlane( this );
  3972. },
  3973. intersectsSphere: function ( sphere ) {
  3974. return sphere.intersectsPlane( this );
  3975. },
  3976. coplanarPoint: function ( optionalTarget ) {
  3977. var result = optionalTarget || new THREE.Vector3();
  3978. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3979. },
  3980. applyMatrix4: function () {
  3981. var v1 = new THREE.Vector3();
  3982. var v2 = new THREE.Vector3();
  3983. var m1 = new THREE.Matrix3();
  3984. return function ( matrix, optionalNormalMatrix ) {
  3985. // compute new normal based on theory here:
  3986. // http://www.songho.ca/opengl/gl_normaltransform.html
  3987. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3988. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3989. var newCoplanarPoint = this.coplanarPoint( v2 );
  3990. newCoplanarPoint.applyMatrix4( matrix );
  3991. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3992. return this;
  3993. };
  3994. }(),
  3995. translate: function ( offset ) {
  3996. this.constant = this.constant - offset.dot( this.normal );
  3997. return this;
  3998. },
  3999. equals: function ( plane ) {
  4000. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4001. }
  4002. };
  4003. // File:src/math/Math.js
  4004. /**
  4005. * @author alteredq / http://alteredqualia.com/
  4006. * @author mrdoob / http://mrdoob.com/
  4007. */
  4008. THREE.Math = {
  4009. generateUUID: function () {
  4010. // http://www.broofa.com/Tools/Math.uuid.htm
  4011. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4012. var uuid = new Array( 36 );
  4013. var rnd = 0, r;
  4014. return function () {
  4015. for ( var i = 0; i < 36; i ++ ) {
  4016. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4017. uuid[ i ] = '-';
  4018. } else if ( i === 14 ) {
  4019. uuid[ i ] = '4';
  4020. } else {
  4021. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4022. r = rnd & 0xf;
  4023. rnd = rnd >> 4;
  4024. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4025. }
  4026. }
  4027. return uuid.join( '' );
  4028. };
  4029. }(),
  4030. clamp: function ( value, min, max ) {
  4031. return Math.max( min, Math.min( max, value ) );
  4032. },
  4033. // compute euclidian modulo of m % n
  4034. // https://en.wikipedia.org/wiki/Modulo_operation
  4035. euclideanModulo: function ( n, m ) {
  4036. return ( ( n % m ) + m ) % m;
  4037. },
  4038. // Linear mapping from range <a1, a2> to range <b1, b2>
  4039. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4040. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4041. },
  4042. // http://en.wikipedia.org/wiki/Smoothstep
  4043. smoothstep: function ( x, min, max ) {
  4044. if ( x <= min ) return 0;
  4045. if ( x >= max ) return 1;
  4046. x = ( x - min ) / ( max - min );
  4047. return x * x * ( 3 - 2 * x );
  4048. },
  4049. smootherstep: function ( x, min, max ) {
  4050. if ( x <= min ) return 0;
  4051. if ( x >= max ) return 1;
  4052. x = ( x - min ) / ( max - min );
  4053. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4054. },
  4055. // Random float from <0, 1> with 16 bits of randomness
  4056. // (standard Math.random() creates repetitive patterns when applied over larger space)
  4057. random16: function () {
  4058. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  4059. },
  4060. // Random integer from <low, high> interval
  4061. randInt: function ( low, high ) {
  4062. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4063. },
  4064. // Random float from <low, high> interval
  4065. randFloat: function ( low, high ) {
  4066. return low + Math.random() * ( high - low );
  4067. },
  4068. // Random float from <-range/2, range/2> interval
  4069. randFloatSpread: function ( range ) {
  4070. return range * ( 0.5 - Math.random() );
  4071. },
  4072. degToRad: function () {
  4073. var degreeToRadiansFactor = Math.PI / 180;
  4074. return function ( degrees ) {
  4075. return degrees * degreeToRadiansFactor;
  4076. };
  4077. }(),
  4078. radToDeg: function () {
  4079. var radianToDegreesFactor = 180 / Math.PI;
  4080. return function ( radians ) {
  4081. return radians * radianToDegreesFactor;
  4082. };
  4083. }(),
  4084. isPowerOfTwo: function ( value ) {
  4085. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4086. },
  4087. nearestPowerOfTwo: function ( value ) {
  4088. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4089. },
  4090. nextPowerOfTwo: function ( value ) {
  4091. value --;
  4092. value |= value >> 1;
  4093. value |= value >> 2;
  4094. value |= value >> 4;
  4095. value |= value >> 8;
  4096. value |= value >> 16;
  4097. value ++;
  4098. return value;
  4099. }
  4100. };
  4101. // File:src/math/Spline.js
  4102. /**
  4103. * Spline from Tween.js, slightly optimized (and trashed)
  4104. * http://sole.github.com/tween.js/examples/05_spline.html
  4105. *
  4106. * @author mrdoob / http://mrdoob.com/
  4107. * @author alteredq / http://alteredqualia.com/
  4108. */
  4109. THREE.Spline = function ( points ) {
  4110. this.points = points;
  4111. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4112. point, intPoint, weight, w2, w3,
  4113. pa, pb, pc, pd;
  4114. this.initFromArray = function ( a ) {
  4115. this.points = [];
  4116. for ( var i = 0; i < a.length; i ++ ) {
  4117. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4118. }
  4119. };
  4120. this.getPoint = function ( k ) {
  4121. point = ( this.points.length - 1 ) * k;
  4122. intPoint = Math.floor( point );
  4123. weight = point - intPoint;
  4124. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4125. c[ 1 ] = intPoint;
  4126. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4127. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4128. pa = this.points[ c[ 0 ] ];
  4129. pb = this.points[ c[ 1 ] ];
  4130. pc = this.points[ c[ 2 ] ];
  4131. pd = this.points[ c[ 3 ] ];
  4132. w2 = weight * weight;
  4133. w3 = weight * w2;
  4134. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4135. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4136. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4137. return v3;
  4138. };
  4139. this.getControlPointsArray = function () {
  4140. var i, p, l = this.points.length,
  4141. coords = [];
  4142. for ( i = 0; i < l; i ++ ) {
  4143. p = this.points[ i ];
  4144. coords[ i ] = [ p.x, p.y, p.z ];
  4145. }
  4146. return coords;
  4147. };
  4148. // approximate length by summing linear segments
  4149. this.getLength = function ( nSubDivisions ) {
  4150. var i, index, nSamples, position,
  4151. point = 0, intPoint = 0, oldIntPoint = 0,
  4152. oldPosition = new THREE.Vector3(),
  4153. tmpVec = new THREE.Vector3(),
  4154. chunkLengths = [],
  4155. totalLength = 0;
  4156. // first point has 0 length
  4157. chunkLengths[ 0 ] = 0;
  4158. if ( ! nSubDivisions ) nSubDivisions = 100;
  4159. nSamples = this.points.length * nSubDivisions;
  4160. oldPosition.copy( this.points[ 0 ] );
  4161. for ( i = 1; i < nSamples; i ++ ) {
  4162. index = i / nSamples;
  4163. position = this.getPoint( index );
  4164. tmpVec.copy( position );
  4165. totalLength += tmpVec.distanceTo( oldPosition );
  4166. oldPosition.copy( position );
  4167. point = ( this.points.length - 1 ) * index;
  4168. intPoint = Math.floor( point );
  4169. if ( intPoint !== oldIntPoint ) {
  4170. chunkLengths[ intPoint ] = totalLength;
  4171. oldIntPoint = intPoint;
  4172. }
  4173. }
  4174. // last point ends with total length
  4175. chunkLengths[ chunkLengths.length ] = totalLength;
  4176. return { chunks: chunkLengths, total: totalLength };
  4177. };
  4178. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4179. var i, j,
  4180. index, indexCurrent, indexNext,
  4181. realDistance,
  4182. sampling, position,
  4183. newpoints = [],
  4184. tmpVec = new THREE.Vector3(),
  4185. sl = this.getLength();
  4186. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4187. for ( i = 1; i < this.points.length; i ++ ) {
  4188. //tmpVec.copy( this.points[ i - 1 ] );
  4189. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4190. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4191. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4192. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4193. indexNext = i / ( this.points.length - 1 );
  4194. for ( j = 1; j < sampling - 1; j ++ ) {
  4195. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4196. position = this.getPoint( index );
  4197. newpoints.push( tmpVec.copy( position ).clone() );
  4198. }
  4199. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4200. }
  4201. this.points = newpoints;
  4202. };
  4203. // Catmull-Rom
  4204. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4205. var v0 = ( p2 - p0 ) * 0.5,
  4206. v1 = ( p3 - p1 ) * 0.5;
  4207. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4208. }
  4209. };
  4210. // File:src/math/Triangle.js
  4211. /**
  4212. * @author bhouston / http://clara.io
  4213. * @author mrdoob / http://mrdoob.com/
  4214. */
  4215. THREE.Triangle = function ( a, b, c ) {
  4216. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4217. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4218. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4219. };
  4220. THREE.Triangle.normal = function () {
  4221. var v0 = new THREE.Vector3();
  4222. return function ( a, b, c, optionalTarget ) {
  4223. var result = optionalTarget || new THREE.Vector3();
  4224. result.subVectors( c, b );
  4225. v0.subVectors( a, b );
  4226. result.cross( v0 );
  4227. var resultLengthSq = result.lengthSq();
  4228. if ( resultLengthSq > 0 ) {
  4229. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4230. }
  4231. return result.set( 0, 0, 0 );
  4232. };
  4233. }();
  4234. // static/instance method to calculate barycentric coordinates
  4235. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4236. THREE.Triangle.barycoordFromPoint = function () {
  4237. var v0 = new THREE.Vector3();
  4238. var v1 = new THREE.Vector3();
  4239. var v2 = new THREE.Vector3();
  4240. return function ( point, a, b, c, optionalTarget ) {
  4241. v0.subVectors( c, a );
  4242. v1.subVectors( b, a );
  4243. v2.subVectors( point, a );
  4244. var dot00 = v0.dot( v0 );
  4245. var dot01 = v0.dot( v1 );
  4246. var dot02 = v0.dot( v2 );
  4247. var dot11 = v1.dot( v1 );
  4248. var dot12 = v1.dot( v2 );
  4249. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4250. var result = optionalTarget || new THREE.Vector3();
  4251. // collinear or singular triangle
  4252. if ( denom === 0 ) {
  4253. // arbitrary location outside of triangle?
  4254. // not sure if this is the best idea, maybe should be returning undefined
  4255. return result.set( - 2, - 1, - 1 );
  4256. }
  4257. var invDenom = 1 / denom;
  4258. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4259. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4260. // barycentric coordinates must always sum to 1
  4261. return result.set( 1 - u - v, v, u );
  4262. };
  4263. }();
  4264. THREE.Triangle.containsPoint = function () {
  4265. var v1 = new THREE.Vector3();
  4266. return function ( point, a, b, c ) {
  4267. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4268. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4269. };
  4270. }();
  4271. THREE.Triangle.prototype = {
  4272. constructor: THREE.Triangle,
  4273. set: function ( a, b, c ) {
  4274. this.a.copy( a );
  4275. this.b.copy( b );
  4276. this.c.copy( c );
  4277. return this;
  4278. },
  4279. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4280. this.a.copy( points[ i0 ] );
  4281. this.b.copy( points[ i1 ] );
  4282. this.c.copy( points[ i2 ] );
  4283. return this;
  4284. },
  4285. clone: function () {
  4286. return new this.constructor().copy( this );
  4287. },
  4288. copy: function ( triangle ) {
  4289. this.a.copy( triangle.a );
  4290. this.b.copy( triangle.b );
  4291. this.c.copy( triangle.c );
  4292. return this;
  4293. },
  4294. area: function () {
  4295. var v0 = new THREE.Vector3();
  4296. var v1 = new THREE.Vector3();
  4297. return function () {
  4298. v0.subVectors( this.c, this.b );
  4299. v1.subVectors( this.a, this.b );
  4300. return v0.cross( v1 ).length() * 0.5;
  4301. };
  4302. }(),
  4303. midpoint: function ( optionalTarget ) {
  4304. var result = optionalTarget || new THREE.Vector3();
  4305. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4306. },
  4307. normal: function ( optionalTarget ) {
  4308. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4309. },
  4310. plane: function ( optionalTarget ) {
  4311. var result = optionalTarget || new THREE.Plane();
  4312. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4313. },
  4314. barycoordFromPoint: function ( point, optionalTarget ) {
  4315. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4316. },
  4317. containsPoint: function ( point ) {
  4318. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4319. },
  4320. equals: function ( triangle ) {
  4321. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4322. }
  4323. };
  4324. // File:src/math/Interpolant.js
  4325. /**
  4326. * Abstract base class of interpolants over parametric samples.
  4327. *
  4328. * The parameter domain is one dimensional, typically the time or a path
  4329. * along a curve defined by the data.
  4330. *
  4331. * The sample values can have any dimensionality and derived classes may
  4332. * apply special interpretations to the data.
  4333. *
  4334. * This class provides the interval seek in a Template Method, deferring
  4335. * the actual interpolation to derived classes.
  4336. *
  4337. * Time complexity is O(1) for linear access crossing at most two points
  4338. * and O(log N) for random access, where N is the number of positions.
  4339. *
  4340. * References:
  4341. *
  4342. * http://www.oodesign.com/template-method-pattern.html
  4343. *
  4344. * @author tschw
  4345. */
  4346. THREE.Interpolant = function(
  4347. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4348. this.parameterPositions = parameterPositions;
  4349. this._cachedIndex = 0;
  4350. this.resultBuffer = resultBuffer !== undefined ?
  4351. resultBuffer : new sampleValues.constructor( sampleSize );
  4352. this.sampleValues = sampleValues;
  4353. this.valueSize = sampleSize;
  4354. };
  4355. THREE.Interpolant.prototype = {
  4356. constructor: THREE.Intepolant,
  4357. evaluate: function( t ) {
  4358. var pp = this.parameterPositions,
  4359. i1 = this._cachedIndex,
  4360. t1 = pp[ i1 ],
  4361. t0 = pp[ i1 - 1 ];
  4362. validate_interval: {
  4363. seek: {
  4364. var right;
  4365. linear_scan: {
  4366. //- See http://jsperf.com/comparison-to-undefined/3
  4367. //- slower code:
  4368. //-
  4369. //- if ( t >= t1 || t1 === undefined ) {
  4370. forward_scan: if ( ! ( t < t1 ) ) {
  4371. for ( var giveUpAt = i1 + 2; ;) {
  4372. if ( t1 === undefined ) {
  4373. if ( t < t0 ) break forward_scan;
  4374. // after end
  4375. i1 = pp.length;
  4376. this._cachedIndex = i1;
  4377. return this.afterEnd_( i1 - 1, t, t0 );
  4378. }
  4379. if ( i1 === giveUpAt ) break; // this loop
  4380. t0 = t1;
  4381. t1 = pp[ ++ i1 ];
  4382. if ( t < t1 ) {
  4383. // we have arrived at the sought interval
  4384. break seek;
  4385. }
  4386. }
  4387. // prepare binary search on the right side of the index
  4388. right = pp.length;
  4389. break linear_scan;
  4390. }
  4391. //- slower code:
  4392. //- if ( t < t0 || t0 === undefined ) {
  4393. if ( ! ( t >= t0 ) ) {
  4394. // looping?
  4395. var t1global = pp[ 1 ];
  4396. if ( t < t1global ) {
  4397. i1 = 2; // + 1, using the scan for the details
  4398. t0 = t1global;
  4399. }
  4400. // linear reverse scan
  4401. for ( var giveUpAt = i1 - 2; ;) {
  4402. if ( t0 === undefined ) {
  4403. // before start
  4404. this._cachedIndex = 0;
  4405. return this.beforeStart_( 0, t, t1 );
  4406. }
  4407. if ( i1 === giveUpAt ) break; // this loop
  4408. t1 = t0;
  4409. t0 = pp[ -- i1 - 1 ];
  4410. if ( t >= t0 ) {
  4411. // we have arrived at the sought interval
  4412. break seek;
  4413. }
  4414. }
  4415. // prepare binary search on the left side of the index
  4416. right = i1;
  4417. i1 = 0;
  4418. break linear_scan;
  4419. }
  4420. // the interval is valid
  4421. break validate_interval;
  4422. } // linear scan
  4423. // binary search
  4424. while ( i1 < right ) {
  4425. var mid = ( i1 + right ) >>> 1;
  4426. if ( t < pp[ mid ] ) {
  4427. right = mid;
  4428. } else {
  4429. i1 = mid + 1;
  4430. }
  4431. }
  4432. t1 = pp[ i1 ];
  4433. t0 = pp[ i1 - 1 ];
  4434. // check boundary cases, again
  4435. if ( t0 === undefined ) {
  4436. this._cachedIndex = 0;
  4437. return this.beforeStart_( 0, t, t1 );
  4438. }
  4439. if ( t1 === undefined ) {
  4440. i1 = pp.length;
  4441. this._cachedIndex = i1;
  4442. return this.afterEnd_( i1 - 1, t0, t );
  4443. }
  4444. } // seek
  4445. this._cachedIndex = i1;
  4446. this.intervalChanged_( i1, t0, t1 );
  4447. } // validate_interval
  4448. return this.interpolate_( i1, t0, t, t1 );
  4449. },
  4450. settings: null, // optional, subclass-specific settings structure
  4451. // Note: The indirection allows central control of many interpolants.
  4452. // --- Protected interface
  4453. DefaultSettings_: {},
  4454. getSettings_: function() {
  4455. return this.settings || this.DefaultSettings_;
  4456. },
  4457. copySampleValue_: function( index ) {
  4458. // copies a sample value to the result buffer
  4459. var result = this.resultBuffer,
  4460. values = this.sampleValues,
  4461. stride = this.valueSize,
  4462. offset = index * stride;
  4463. for ( var i = 0; i !== stride; ++ i ) {
  4464. result[ i ] = values[ offset + i ];
  4465. }
  4466. return result;
  4467. },
  4468. // Template methods for derived classes:
  4469. interpolate_: function( i1, t0, t, t1 ) {
  4470. throw new Error( "call to abstract method" );
  4471. // implementations shall return this.resultBuffer
  4472. },
  4473. intervalChanged_: function( i1, t0, t1 ) {
  4474. // empty
  4475. }
  4476. };
  4477. Object.assign( THREE.Interpolant.prototype, {
  4478. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4479. THREE.Interpolant.prototype.copySampleValue_,
  4480. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4481. THREE.Interpolant.prototype.copySampleValue_
  4482. } );
  4483. // File:src/math/interpolants/CubicInterpolant.js
  4484. /**
  4485. * Fast and simple cubic spline interpolant.
  4486. *
  4487. * It was derived from a Hermitian construction setting the first derivative
  4488. * at each sample position to the linear slope between neighboring positions
  4489. * over their parameter interval.
  4490. *
  4491. * @author tschw
  4492. */
  4493. THREE.CubicInterpolant = function(
  4494. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4495. THREE.Interpolant.call(
  4496. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4497. this._weightPrev = -0;
  4498. this._offsetPrev = -0;
  4499. this._weightNext = -0;
  4500. this._offsetNext = -0;
  4501. };
  4502. THREE.CubicInterpolant.prototype =
  4503. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4504. constructor: THREE.CubicInterpolant,
  4505. DefaultSettings_: {
  4506. endingStart: THREE.ZeroCurvatureEnding,
  4507. endingEnd: THREE.ZeroCurvatureEnding
  4508. },
  4509. intervalChanged_: function( i1, t0, t1 ) {
  4510. var pp = this.parameterPositions,
  4511. iPrev = i1 - 2,
  4512. iNext = i1 + 1,
  4513. tPrev = pp[ iPrev ],
  4514. tNext = pp[ iNext ];
  4515. if ( tPrev === undefined ) {
  4516. switch ( this.getSettings_().endingStart ) {
  4517. case THREE.ZeroSlopeEnding:
  4518. // f'(t0) = 0
  4519. iPrev = i1;
  4520. tPrev = 2 * t0 - t1;
  4521. break;
  4522. case THREE.WrapAroundEnding:
  4523. // use the other end of the curve
  4524. iPrev = pp.length - 2;
  4525. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4526. break;
  4527. default: // ZeroCurvatureEnding
  4528. // f''(t0) = 0 a.k.a. Natural Spline
  4529. iPrev = i1;
  4530. tPrev = t1;
  4531. }
  4532. }
  4533. if ( tNext === undefined ) {
  4534. switch ( this.getSettings_().endingEnd ) {
  4535. case THREE.ZeroSlopeEnding:
  4536. // f'(tN) = 0
  4537. iNext = i1;
  4538. tNext = 2 * t1 - t0;
  4539. break;
  4540. case THREE.WrapAroundEnding:
  4541. // use the other end of the curve
  4542. iNext = 1;
  4543. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4544. break;
  4545. default: // ZeroCurvatureEnding
  4546. // f''(tN) = 0, a.k.a. Natural Spline
  4547. iNext = i1 - 1;
  4548. tNext = t0;
  4549. }
  4550. }
  4551. var halfDt = ( t1 - t0 ) * 0.5,
  4552. stride = this.valueSize;
  4553. this._weightPrev = halfDt / ( t0 - tPrev );
  4554. this._weightNext = halfDt / ( tNext - t1 );
  4555. this._offsetPrev = iPrev * stride;
  4556. this._offsetNext = iNext * stride;
  4557. },
  4558. interpolate_: function( i1, t0, t, t1 ) {
  4559. var result = this.resultBuffer,
  4560. values = this.sampleValues,
  4561. stride = this.valueSize,
  4562. o1 = i1 * stride, o0 = o1 - stride,
  4563. oP = this._offsetPrev, oN = this._offsetNext,
  4564. wP = this._weightPrev, wN = this._weightNext,
  4565. p = ( t - t0 ) / ( t1 - t0 ),
  4566. pp = p * p,
  4567. ppp = pp * p;
  4568. // evaluate polynomials
  4569. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4570. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4571. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4572. var sN = wN * ppp - wN * pp;
  4573. // combine data linearly
  4574. for ( var i = 0; i !== stride; ++ i ) {
  4575. result[ i ] =
  4576. sP * values[ oP + i ] +
  4577. s0 * values[ o0 + i ] +
  4578. s1 * values[ o1 + i ] +
  4579. sN * values[ oN + i ];
  4580. }
  4581. return result;
  4582. }
  4583. } );
  4584. // File:src/math/interpolants/DiscreteInterpolant.js
  4585. /**
  4586. *
  4587. * Interpolant that evaluates to the sample value at the position preceeding
  4588. * the parameter.
  4589. *
  4590. * @author tschw
  4591. */
  4592. THREE.DiscreteInterpolant = function(
  4593. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4594. THREE.Interpolant.call(
  4595. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4596. };
  4597. THREE.DiscreteInterpolant.prototype =
  4598. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4599. constructor: THREE.DiscreteInterpolant,
  4600. interpolate_: function( i1, t0, t, t1 ) {
  4601. return this.copySampleValue_( i1 - 1 );
  4602. }
  4603. } );
  4604. // File:src/math/interpolants/LinearInterpolant.js
  4605. /**
  4606. * @author tschw
  4607. */
  4608. THREE.LinearInterpolant = function(
  4609. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4610. THREE.Interpolant.call(
  4611. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4612. };
  4613. THREE.LinearInterpolant.prototype =
  4614. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4615. constructor: THREE.LinearInterpolant,
  4616. interpolate_: function( i1, t0, t, t1 ) {
  4617. var result = this.resultBuffer,
  4618. values = this.sampleValues,
  4619. stride = this.valueSize,
  4620. offset1 = i1 * stride,
  4621. offset0 = offset1 - stride,
  4622. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4623. weight0 = 1 - weight1;
  4624. for ( var i = 0; i !== stride; ++ i ) {
  4625. result[ i ] =
  4626. values[ offset0 + i ] * weight0 +
  4627. values[ offset1 + i ] * weight1;
  4628. }
  4629. return result;
  4630. }
  4631. } );
  4632. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4633. /**
  4634. * Spherical linear unit quaternion interpolant.
  4635. *
  4636. * @author tschw
  4637. */
  4638. THREE.QuaternionLinearInterpolant = function(
  4639. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4640. THREE.Interpolant.call(
  4641. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4642. };
  4643. THREE.QuaternionLinearInterpolant.prototype =
  4644. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4645. constructor: THREE.QuaternionLinearInterpolant,
  4646. interpolate_: function( i1, t0, t, t1 ) {
  4647. var result = this.resultBuffer,
  4648. values = this.sampleValues,
  4649. stride = this.valueSize,
  4650. offset = i1 * stride,
  4651. alpha = ( t - t0 ) / ( t1 - t0 );
  4652. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4653. THREE.Quaternion.slerpFlat( result, 0,
  4654. values, offset - stride, values, offset, alpha );
  4655. }
  4656. return result;
  4657. }
  4658. } );
  4659. // File:src/core/Clock.js
  4660. /**
  4661. * @author alteredq / http://alteredqualia.com/
  4662. */
  4663. THREE.Clock = function ( autoStart ) {
  4664. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4665. this.startTime = 0;
  4666. this.oldTime = 0;
  4667. this.elapsedTime = 0;
  4668. this.running = false;
  4669. };
  4670. THREE.Clock.prototype = {
  4671. constructor: THREE.Clock,
  4672. start: function () {
  4673. this.startTime = self.performance.now();
  4674. this.oldTime = this.startTime;
  4675. this.running = true;
  4676. },
  4677. stop: function () {
  4678. this.getElapsedTime();
  4679. this.running = false;
  4680. },
  4681. getElapsedTime: function () {
  4682. this.getDelta();
  4683. return this.elapsedTime;
  4684. },
  4685. getDelta: function () {
  4686. var diff = 0;
  4687. if ( this.autoStart && ! this.running ) {
  4688. this.start();
  4689. }
  4690. if ( this.running ) {
  4691. var newTime = self.performance.now();
  4692. diff = 0.001 * ( newTime - this.oldTime );
  4693. this.oldTime = newTime;
  4694. this.elapsedTime += diff;
  4695. }
  4696. return diff;
  4697. }
  4698. };
  4699. // File:src/core/EventDispatcher.js
  4700. /**
  4701. * https://github.com/mrdoob/eventdispatcher.js/
  4702. */
  4703. THREE.EventDispatcher = function () {};
  4704. THREE.EventDispatcher.prototype = {
  4705. constructor: THREE.EventDispatcher,
  4706. apply: function ( object ) {
  4707. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4708. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4709. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4710. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4711. },
  4712. addEventListener: function ( type, listener ) {
  4713. if ( this._listeners === undefined ) this._listeners = {};
  4714. var listeners = this._listeners;
  4715. if ( listeners[ type ] === undefined ) {
  4716. listeners[ type ] = [];
  4717. }
  4718. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4719. listeners[ type ].push( listener );
  4720. }
  4721. },
  4722. hasEventListener: function ( type, listener ) {
  4723. if ( this._listeners === undefined ) return false;
  4724. var listeners = this._listeners;
  4725. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4726. return true;
  4727. }
  4728. return false;
  4729. },
  4730. removeEventListener: function ( type, listener ) {
  4731. if ( this._listeners === undefined ) return;
  4732. var listeners = this._listeners;
  4733. var listenerArray = listeners[ type ];
  4734. if ( listenerArray !== undefined ) {
  4735. var index = listenerArray.indexOf( listener );
  4736. if ( index !== - 1 ) {
  4737. listenerArray.splice( index, 1 );
  4738. }
  4739. }
  4740. },
  4741. dispatchEvent: function ( event ) {
  4742. if ( this._listeners === undefined ) return;
  4743. var listeners = this._listeners;
  4744. var listenerArray = listeners[ event.type ];
  4745. if ( listenerArray !== undefined ) {
  4746. event.target = this;
  4747. var array = [];
  4748. var length = listenerArray.length;
  4749. for ( var i = 0; i < length; i ++ ) {
  4750. array[ i ] = listenerArray[ i ];
  4751. }
  4752. for ( var i = 0; i < length; i ++ ) {
  4753. array[ i ].call( this, event );
  4754. }
  4755. }
  4756. }
  4757. };
  4758. // File:src/core/Layers.js
  4759. /**
  4760. * @author mrdoob / http://mrdoob.com/
  4761. */
  4762. THREE.Layers = function () {
  4763. this.mask = 1;
  4764. };
  4765. THREE.Layers.prototype = {
  4766. constructor: THREE.Layers,
  4767. set: function ( channel ) {
  4768. this.mask = 1 << channel;
  4769. },
  4770. enable: function ( channel ) {
  4771. this.mask |= 1 << channel;
  4772. },
  4773. toggle: function ( channel ) {
  4774. this.mask ^= 1 << channel;
  4775. },
  4776. disable: function ( channel ) {
  4777. this.mask &= ~ ( 1 << channel );
  4778. },
  4779. test: function ( layers ) {
  4780. return ( this.mask & layers.mask ) !== 0;
  4781. }
  4782. };
  4783. // File:src/core/Raycaster.js
  4784. /**
  4785. * @author mrdoob / http://mrdoob.com/
  4786. * @author bhouston / http://clara.io/
  4787. * @author stephomi / http://stephaneginier.com/
  4788. */
  4789. ( function ( THREE ) {
  4790. THREE.Raycaster = function ( origin, direction, near, far ) {
  4791. this.ray = new THREE.Ray( origin, direction );
  4792. // direction is assumed to be normalized (for accurate distance calculations)
  4793. this.near = near || 0;
  4794. this.far = far || Infinity;
  4795. this.params = {
  4796. Mesh: {},
  4797. Line: {},
  4798. LOD: {},
  4799. Points: { threshold: 1 },
  4800. Sprite: {}
  4801. };
  4802. Object.defineProperties( this.params, {
  4803. PointCloud: {
  4804. get: function () {
  4805. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4806. return this.Points;
  4807. }
  4808. }
  4809. } );
  4810. };
  4811. function descSort( a, b ) {
  4812. return a.distance - b.distance;
  4813. }
  4814. function intersectObject( object, raycaster, intersects, recursive ) {
  4815. if ( object.visible === false ) return;
  4816. object.raycast( raycaster, intersects );
  4817. if ( recursive === true ) {
  4818. var children = object.children;
  4819. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4820. intersectObject( children[ i ], raycaster, intersects, true );
  4821. }
  4822. }
  4823. }
  4824. //
  4825. THREE.Raycaster.prototype = {
  4826. constructor: THREE.Raycaster,
  4827. linePrecision: 1,
  4828. set: function ( origin, direction ) {
  4829. // direction is assumed to be normalized (for accurate distance calculations)
  4830. this.ray.set( origin, direction );
  4831. },
  4832. setFromCamera: function ( coords, camera ) {
  4833. if ( camera instanceof THREE.PerspectiveCamera ) {
  4834. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4835. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4836. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4837. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4838. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4839. } else {
  4840. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4841. }
  4842. },
  4843. intersectObject: function ( object, recursive ) {
  4844. var intersects = [];
  4845. intersectObject( object, this, intersects, recursive );
  4846. intersects.sort( descSort );
  4847. return intersects;
  4848. },
  4849. intersectObjects: function ( objects, recursive ) {
  4850. var intersects = [];
  4851. if ( Array.isArray( objects ) === false ) {
  4852. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4853. return intersects;
  4854. }
  4855. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4856. intersectObject( objects[ i ], this, intersects, recursive );
  4857. }
  4858. intersects.sort( descSort );
  4859. return intersects;
  4860. }
  4861. };
  4862. }( THREE ) );
  4863. // File:src/core/Object3D.js
  4864. /**
  4865. * @author mrdoob / http://mrdoob.com/
  4866. * @author mikael emtinger / http://gomo.se/
  4867. * @author alteredq / http://alteredqualia.com/
  4868. * @author WestLangley / http://github.com/WestLangley
  4869. * @author elephantatwork / www.elephantatwork.ch
  4870. */
  4871. THREE.Object3D = function () {
  4872. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4873. this.uuid = THREE.Math.generateUUID();
  4874. this.name = '';
  4875. this.type = 'Object3D';
  4876. this.parent = null;
  4877. this.children = [];
  4878. this.up = THREE.Object3D.DefaultUp.clone();
  4879. var position = new THREE.Vector3();
  4880. var rotation = new THREE.Euler();
  4881. var quaternion = new THREE.Quaternion();
  4882. var scale = new THREE.Vector3( 1, 1, 1 );
  4883. function onRotationChange() {
  4884. quaternion.setFromEuler( rotation, false );
  4885. }
  4886. function onQuaternionChange() {
  4887. rotation.setFromQuaternion( quaternion, undefined, false );
  4888. }
  4889. rotation.onChange( onRotationChange );
  4890. quaternion.onChange( onQuaternionChange );
  4891. Object.defineProperties( this, {
  4892. position: {
  4893. enumerable: true,
  4894. value: position
  4895. },
  4896. rotation: {
  4897. enumerable: true,
  4898. value: rotation
  4899. },
  4900. quaternion: {
  4901. enumerable: true,
  4902. value: quaternion
  4903. },
  4904. scale: {
  4905. enumerable: true,
  4906. value: scale
  4907. },
  4908. modelViewMatrix: {
  4909. value: new THREE.Matrix4()
  4910. },
  4911. normalMatrix: {
  4912. value: new THREE.Matrix3()
  4913. }
  4914. } );
  4915. this.rotationAutoUpdate = true;
  4916. this.matrix = new THREE.Matrix4();
  4917. this.matrixWorld = new THREE.Matrix4();
  4918. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  4919. this.matrixWorldNeedsUpdate = false;
  4920. this.layers = new THREE.Layers();
  4921. this.visible = true;
  4922. this.castShadow = false;
  4923. this.receiveShadow = false;
  4924. this.frustumCulled = true;
  4925. this.renderOrder = 0;
  4926. this.userData = {};
  4927. };
  4928. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4929. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  4930. THREE.Object3D.prototype = {
  4931. constructor: THREE.Object3D,
  4932. applyMatrix: function ( matrix ) {
  4933. this.matrix.multiplyMatrices( matrix, this.matrix );
  4934. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4935. },
  4936. setRotationFromAxisAngle: function ( axis, angle ) {
  4937. // assumes axis is normalized
  4938. this.quaternion.setFromAxisAngle( axis, angle );
  4939. },
  4940. setRotationFromEuler: function ( euler ) {
  4941. this.quaternion.setFromEuler( euler, true );
  4942. },
  4943. setRotationFromMatrix: function ( m ) {
  4944. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4945. this.quaternion.setFromRotationMatrix( m );
  4946. },
  4947. setRotationFromQuaternion: function ( q ) {
  4948. // assumes q is normalized
  4949. this.quaternion.copy( q );
  4950. },
  4951. rotateOnAxis: function () {
  4952. // rotate object on axis in object space
  4953. // axis is assumed to be normalized
  4954. var q1 = new THREE.Quaternion();
  4955. return function ( axis, angle ) {
  4956. q1.setFromAxisAngle( axis, angle );
  4957. this.quaternion.multiply( q1 );
  4958. return this;
  4959. };
  4960. }(),
  4961. rotateX: function () {
  4962. var v1 = new THREE.Vector3( 1, 0, 0 );
  4963. return function ( angle ) {
  4964. return this.rotateOnAxis( v1, angle );
  4965. };
  4966. }(),
  4967. rotateY: function () {
  4968. var v1 = new THREE.Vector3( 0, 1, 0 );
  4969. return function ( angle ) {
  4970. return this.rotateOnAxis( v1, angle );
  4971. };
  4972. }(),
  4973. rotateZ: function () {
  4974. var v1 = new THREE.Vector3( 0, 0, 1 );
  4975. return function ( angle ) {
  4976. return this.rotateOnAxis( v1, angle );
  4977. };
  4978. }(),
  4979. translateOnAxis: function () {
  4980. // translate object by distance along axis in object space
  4981. // axis is assumed to be normalized
  4982. var v1 = new THREE.Vector3();
  4983. return function ( axis, distance ) {
  4984. v1.copy( axis ).applyQuaternion( this.quaternion );
  4985. this.position.add( v1.multiplyScalar( distance ) );
  4986. return this;
  4987. };
  4988. }(),
  4989. translateX: function () {
  4990. var v1 = new THREE.Vector3( 1, 0, 0 );
  4991. return function ( distance ) {
  4992. return this.translateOnAxis( v1, distance );
  4993. };
  4994. }(),
  4995. translateY: function () {
  4996. var v1 = new THREE.Vector3( 0, 1, 0 );
  4997. return function ( distance ) {
  4998. return this.translateOnAxis( v1, distance );
  4999. };
  5000. }(),
  5001. translateZ: function () {
  5002. var v1 = new THREE.Vector3( 0, 0, 1 );
  5003. return function ( distance ) {
  5004. return this.translateOnAxis( v1, distance );
  5005. };
  5006. }(),
  5007. localToWorld: function ( vector ) {
  5008. return vector.applyMatrix4( this.matrixWorld );
  5009. },
  5010. worldToLocal: function () {
  5011. var m1 = new THREE.Matrix4();
  5012. return function ( vector ) {
  5013. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5014. };
  5015. }(),
  5016. lookAt: function () {
  5017. // This routine does not support objects with rotated and/or translated parent(s)
  5018. var m1 = new THREE.Matrix4();
  5019. return function ( vector ) {
  5020. m1.lookAt( vector, this.position, this.up );
  5021. this.quaternion.setFromRotationMatrix( m1 );
  5022. };
  5023. }(),
  5024. add: function ( object ) {
  5025. if ( arguments.length > 1 ) {
  5026. for ( var i = 0; i < arguments.length; i ++ ) {
  5027. this.add( arguments[ i ] );
  5028. }
  5029. return this;
  5030. }
  5031. if ( object === this ) {
  5032. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5033. return this;
  5034. }
  5035. if ( object instanceof THREE.Object3D ) {
  5036. if ( object.parent !== null ) {
  5037. object.parent.remove( object );
  5038. }
  5039. object.parent = this;
  5040. object.dispatchEvent( { type: 'added' } );
  5041. this.children.push( object );
  5042. } else {
  5043. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5044. }
  5045. return this;
  5046. },
  5047. remove: function ( object ) {
  5048. if ( arguments.length > 1 ) {
  5049. for ( var i = 0; i < arguments.length; i ++ ) {
  5050. this.remove( arguments[ i ] );
  5051. }
  5052. }
  5053. var index = this.children.indexOf( object );
  5054. if ( index !== - 1 ) {
  5055. object.parent = null;
  5056. object.dispatchEvent( { type: 'removed' } );
  5057. this.children.splice( index, 1 );
  5058. }
  5059. },
  5060. getObjectById: function ( id ) {
  5061. return this.getObjectByProperty( 'id', id );
  5062. },
  5063. getObjectByName: function ( name ) {
  5064. return this.getObjectByProperty( 'name', name );
  5065. },
  5066. getObjectByProperty: function ( name, value ) {
  5067. if ( this[ name ] === value ) return this;
  5068. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5069. var child = this.children[ i ];
  5070. var object = child.getObjectByProperty( name, value );
  5071. if ( object !== undefined ) {
  5072. return object;
  5073. }
  5074. }
  5075. return undefined;
  5076. },
  5077. getWorldPosition: function ( optionalTarget ) {
  5078. var result = optionalTarget || new THREE.Vector3();
  5079. this.updateMatrixWorld( true );
  5080. return result.setFromMatrixPosition( this.matrixWorld );
  5081. },
  5082. getWorldQuaternion: function () {
  5083. var position = new THREE.Vector3();
  5084. var scale = new THREE.Vector3();
  5085. return function ( optionalTarget ) {
  5086. var result = optionalTarget || new THREE.Quaternion();
  5087. this.updateMatrixWorld( true );
  5088. this.matrixWorld.decompose( position, result, scale );
  5089. return result;
  5090. };
  5091. }(),
  5092. getWorldRotation: function () {
  5093. var quaternion = new THREE.Quaternion();
  5094. return function ( optionalTarget ) {
  5095. var result = optionalTarget || new THREE.Euler();
  5096. this.getWorldQuaternion( quaternion );
  5097. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5098. };
  5099. }(),
  5100. getWorldScale: function () {
  5101. var position = new THREE.Vector3();
  5102. var quaternion = new THREE.Quaternion();
  5103. return function ( optionalTarget ) {
  5104. var result = optionalTarget || new THREE.Vector3();
  5105. this.updateMatrixWorld( true );
  5106. this.matrixWorld.decompose( position, quaternion, result );
  5107. return result;
  5108. };
  5109. }(),
  5110. getWorldDirection: function () {
  5111. var quaternion = new THREE.Quaternion();
  5112. return function ( optionalTarget ) {
  5113. var result = optionalTarget || new THREE.Vector3();
  5114. this.getWorldQuaternion( quaternion );
  5115. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5116. };
  5117. }(),
  5118. raycast: function () {},
  5119. traverse: function ( callback ) {
  5120. callback( this );
  5121. var children = this.children;
  5122. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5123. children[ i ].traverse( callback );
  5124. }
  5125. },
  5126. traverseVisible: function ( callback ) {
  5127. if ( this.visible === false ) return;
  5128. callback( this );
  5129. var children = this.children;
  5130. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5131. children[ i ].traverseVisible( callback );
  5132. }
  5133. },
  5134. traverseAncestors: function ( callback ) {
  5135. var parent = this.parent;
  5136. if ( parent !== null ) {
  5137. callback( parent );
  5138. parent.traverseAncestors( callback );
  5139. }
  5140. },
  5141. updateMatrix: function () {
  5142. this.matrix.compose( this.position, this.quaternion, this.scale );
  5143. this.matrixWorldNeedsUpdate = true;
  5144. },
  5145. updateMatrixWorld: function ( force ) {
  5146. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5147. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5148. if ( this.parent === null ) {
  5149. this.matrixWorld.copy( this.matrix );
  5150. } else {
  5151. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5152. }
  5153. this.matrixWorldNeedsUpdate = false;
  5154. force = true;
  5155. }
  5156. // update children
  5157. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5158. this.children[ i ].updateMatrixWorld( force );
  5159. }
  5160. },
  5161. toJSON: function ( meta ) {
  5162. var isRootObject = ( meta === undefined );
  5163. var output = {};
  5164. // meta is a hash used to collect geometries, materials.
  5165. // not providing it implies that this is the root object
  5166. // being serialized.
  5167. if ( isRootObject ) {
  5168. // initialize meta obj
  5169. meta = {
  5170. geometries: {},
  5171. materials: {},
  5172. textures: {},
  5173. images: {}
  5174. };
  5175. output.metadata = {
  5176. version: 4.4,
  5177. type: 'Object',
  5178. generator: 'Object3D.toJSON'
  5179. };
  5180. }
  5181. // standard Object3D serialization
  5182. var object = {};
  5183. object.uuid = this.uuid;
  5184. object.type = this.type;
  5185. if ( this.name !== '' ) object.name = this.name;
  5186. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5187. if ( this.castShadow === true ) object.castShadow = true;
  5188. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5189. if ( this.visible === false ) object.visible = false;
  5190. object.matrix = this.matrix.toArray();
  5191. //
  5192. if ( this.geometry !== undefined ) {
  5193. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5194. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5195. }
  5196. object.geometry = this.geometry.uuid;
  5197. }
  5198. if ( this.material !== undefined ) {
  5199. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5200. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5201. }
  5202. object.material = this.material.uuid;
  5203. }
  5204. //
  5205. if ( this.children.length > 0 ) {
  5206. object.children = [];
  5207. for ( var i = 0; i < this.children.length; i ++ ) {
  5208. object.children.push( this.children[ i ].toJSON( meta ).object );
  5209. }
  5210. }
  5211. if ( isRootObject ) {
  5212. var geometries = extractFromCache( meta.geometries );
  5213. var materials = extractFromCache( meta.materials );
  5214. var textures = extractFromCache( meta.textures );
  5215. var images = extractFromCache( meta.images );
  5216. if ( geometries.length > 0 ) output.geometries = geometries;
  5217. if ( materials.length > 0 ) output.materials = materials;
  5218. if ( textures.length > 0 ) output.textures = textures;
  5219. if ( images.length > 0 ) output.images = images;
  5220. }
  5221. output.object = object;
  5222. return output;
  5223. // extract data from the cache hash
  5224. // remove metadata on each item
  5225. // and return as array
  5226. function extractFromCache ( cache ) {
  5227. var values = [];
  5228. for ( var key in cache ) {
  5229. var data = cache[ key ];
  5230. delete data.metadata;
  5231. values.push( data );
  5232. }
  5233. return values;
  5234. }
  5235. },
  5236. clone: function ( recursive ) {
  5237. return new this.constructor().copy( this, recursive );
  5238. },
  5239. copy: function ( source, recursive ) {
  5240. if ( recursive === undefined ) recursive = true;
  5241. this.name = source.name;
  5242. this.up.copy( source.up );
  5243. this.position.copy( source.position );
  5244. this.quaternion.copy( source.quaternion );
  5245. this.scale.copy( source.scale );
  5246. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5247. this.matrix.copy( source.matrix );
  5248. this.matrixWorld.copy( source.matrixWorld );
  5249. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5250. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5251. this.visible = source.visible;
  5252. this.castShadow = source.castShadow;
  5253. this.receiveShadow = source.receiveShadow;
  5254. this.frustumCulled = source.frustumCulled;
  5255. this.renderOrder = source.renderOrder;
  5256. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5257. if ( recursive === true ) {
  5258. for ( var i = 0; i < source.children.length; i ++ ) {
  5259. var child = source.children[ i ];
  5260. this.add( child.clone() );
  5261. }
  5262. }
  5263. return this;
  5264. }
  5265. };
  5266. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5267. THREE.Object3DIdCount = 0;
  5268. // File:src/core/Face3.js
  5269. /**
  5270. * @author mrdoob / http://mrdoob.com/
  5271. * @author alteredq / http://alteredqualia.com/
  5272. */
  5273. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5274. this.a = a;
  5275. this.b = b;
  5276. this.c = c;
  5277. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5278. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5279. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5280. this.vertexColors = Array.isArray( color ) ? color : [];
  5281. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5282. };
  5283. THREE.Face3.prototype = {
  5284. constructor: THREE.Face3,
  5285. clone: function () {
  5286. return new this.constructor().copy( this );
  5287. },
  5288. copy: function ( source ) {
  5289. this.a = source.a;
  5290. this.b = source.b;
  5291. this.c = source.c;
  5292. this.normal.copy( source.normal );
  5293. this.color.copy( source.color );
  5294. this.materialIndex = source.materialIndex;
  5295. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5296. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5297. }
  5298. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5299. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5300. }
  5301. return this;
  5302. }
  5303. };
  5304. // File:src/core/Face4.js
  5305. /**
  5306. * @author mrdoob / http://mrdoob.com/
  5307. */
  5308. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5309. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  5310. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5311. };
  5312. // File:src/core/BufferAttribute.js
  5313. /**
  5314. * @author mrdoob / http://mrdoob.com/
  5315. */
  5316. THREE.BufferAttribute = function ( array, itemSize ) {
  5317. this.uuid = THREE.Math.generateUUID();
  5318. this.array = array;
  5319. this.itemSize = itemSize;
  5320. this.dynamic = false;
  5321. this.updateRange = { offset: 0, count: - 1 };
  5322. this.version = 0;
  5323. };
  5324. THREE.BufferAttribute.prototype = {
  5325. constructor: THREE.BufferAttribute,
  5326. get count() {
  5327. return this.array.length / this.itemSize;
  5328. },
  5329. set needsUpdate( value ) {
  5330. if ( value === true ) this.version ++;
  5331. },
  5332. setDynamic: function ( value ) {
  5333. this.dynamic = value;
  5334. return this;
  5335. },
  5336. copy: function ( source ) {
  5337. this.array = new source.array.constructor( source.array );
  5338. this.itemSize = source.itemSize;
  5339. this.dynamic = source.dynamic;
  5340. return this;
  5341. },
  5342. copyAt: function ( index1, attribute, index2 ) {
  5343. index1 *= this.itemSize;
  5344. index2 *= attribute.itemSize;
  5345. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5346. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5347. }
  5348. return this;
  5349. },
  5350. copyArray: function ( array ) {
  5351. this.array.set( array );
  5352. return this;
  5353. },
  5354. copyColorsArray: function ( colors ) {
  5355. var array = this.array, offset = 0;
  5356. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5357. var color = colors[ i ];
  5358. if ( color === undefined ) {
  5359. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5360. color = new THREE.Color();
  5361. }
  5362. array[ offset ++ ] = color.r;
  5363. array[ offset ++ ] = color.g;
  5364. array[ offset ++ ] = color.b;
  5365. }
  5366. return this;
  5367. },
  5368. copyIndicesArray: function ( indices ) {
  5369. var array = this.array, offset = 0;
  5370. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5371. var index = indices[ i ];
  5372. array[ offset ++ ] = index.a;
  5373. array[ offset ++ ] = index.b;
  5374. array[ offset ++ ] = index.c;
  5375. }
  5376. return this;
  5377. },
  5378. copyVector2sArray: function ( vectors ) {
  5379. var array = this.array, offset = 0;
  5380. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5381. var vector = vectors[ i ];
  5382. if ( vector === undefined ) {
  5383. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5384. vector = new THREE.Vector2();
  5385. }
  5386. array[ offset ++ ] = vector.x;
  5387. array[ offset ++ ] = vector.y;
  5388. }
  5389. return this;
  5390. },
  5391. copyVector3sArray: function ( vectors ) {
  5392. var array = this.array, offset = 0;
  5393. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5394. var vector = vectors[ i ];
  5395. if ( vector === undefined ) {
  5396. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5397. vector = new THREE.Vector3();
  5398. }
  5399. array[ offset ++ ] = vector.x;
  5400. array[ offset ++ ] = vector.y;
  5401. array[ offset ++ ] = vector.z;
  5402. }
  5403. return this;
  5404. },
  5405. copyVector4sArray: function ( vectors ) {
  5406. var array = this.array, offset = 0;
  5407. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5408. var vector = vectors[ i ];
  5409. if ( vector === undefined ) {
  5410. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5411. vector = new THREE.Vector4();
  5412. }
  5413. array[ offset ++ ] = vector.x;
  5414. array[ offset ++ ] = vector.y;
  5415. array[ offset ++ ] = vector.z;
  5416. array[ offset ++ ] = vector.w;
  5417. }
  5418. return this;
  5419. },
  5420. set: function ( value, offset ) {
  5421. if ( offset === undefined ) offset = 0;
  5422. this.array.set( value, offset );
  5423. return this;
  5424. },
  5425. getX: function ( index ) {
  5426. return this.array[ index * this.itemSize ];
  5427. },
  5428. setX: function ( index, x ) {
  5429. this.array[ index * this.itemSize ] = x;
  5430. return this;
  5431. },
  5432. getY: function ( index ) {
  5433. return this.array[ index * this.itemSize + 1 ];
  5434. },
  5435. setY: function ( index, y ) {
  5436. this.array[ index * this.itemSize + 1 ] = y;
  5437. return this;
  5438. },
  5439. getZ: function ( index ) {
  5440. return this.array[ index * this.itemSize + 2 ];
  5441. },
  5442. setZ: function ( index, z ) {
  5443. this.array[ index * this.itemSize + 2 ] = z;
  5444. return this;
  5445. },
  5446. getW: function ( index ) {
  5447. return this.array[ index * this.itemSize + 3 ];
  5448. },
  5449. setW: function ( index, w ) {
  5450. this.array[ index * this.itemSize + 3 ] = w;
  5451. return this;
  5452. },
  5453. setXY: function ( index, x, y ) {
  5454. index *= this.itemSize;
  5455. this.array[ index + 0 ] = x;
  5456. this.array[ index + 1 ] = y;
  5457. return this;
  5458. },
  5459. setXYZ: function ( index, x, y, z ) {
  5460. index *= this.itemSize;
  5461. this.array[ index + 0 ] = x;
  5462. this.array[ index + 1 ] = y;
  5463. this.array[ index + 2 ] = z;
  5464. return this;
  5465. },
  5466. setXYZW: function ( index, x, y, z, w ) {
  5467. index *= this.itemSize;
  5468. this.array[ index + 0 ] = x;
  5469. this.array[ index + 1 ] = y;
  5470. this.array[ index + 2 ] = z;
  5471. this.array[ index + 3 ] = w;
  5472. return this;
  5473. },
  5474. clone: function () {
  5475. return new this.constructor().copy( this );
  5476. }
  5477. };
  5478. //
  5479. THREE.Int8Attribute = function ( array, itemSize ) {
  5480. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5481. };
  5482. THREE.Uint8Attribute = function ( array, itemSize ) {
  5483. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5484. };
  5485. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5486. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5487. };
  5488. THREE.Int16Attribute = function ( array, itemSize ) {
  5489. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5490. };
  5491. THREE.Uint16Attribute = function ( array, itemSize ) {
  5492. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5493. };
  5494. THREE.Int32Attribute = function ( array, itemSize ) {
  5495. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5496. };
  5497. THREE.Uint32Attribute = function ( array, itemSize ) {
  5498. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5499. };
  5500. THREE.Float32Attribute = function ( array, itemSize ) {
  5501. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5502. };
  5503. THREE.Float64Attribute = function ( array, itemSize ) {
  5504. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5505. };
  5506. // Deprecated
  5507. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5508. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5509. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5510. };
  5511. // File:src/core/InstancedBufferAttribute.js
  5512. /**
  5513. * @author benaadams / https://twitter.com/ben_a_adams
  5514. */
  5515. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5516. THREE.BufferAttribute.call( this, array, itemSize );
  5517. this.meshPerAttribute = meshPerAttribute || 1;
  5518. };
  5519. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5520. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5521. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5522. THREE.BufferAttribute.prototype.copy.call( this, source );
  5523. this.meshPerAttribute = source.meshPerAttribute;
  5524. return this;
  5525. };
  5526. // File:src/core/InterleavedBuffer.js
  5527. /**
  5528. * @author benaadams / https://twitter.com/ben_a_adams
  5529. */
  5530. THREE.InterleavedBuffer = function ( array, stride ) {
  5531. this.uuid = THREE.Math.generateUUID();
  5532. this.array = array;
  5533. this.stride = stride;
  5534. this.dynamic = false;
  5535. this.updateRange = { offset: 0, count: - 1 };
  5536. this.version = 0;
  5537. };
  5538. THREE.InterleavedBuffer.prototype = {
  5539. constructor: THREE.InterleavedBuffer,
  5540. get length () {
  5541. return this.array.length;
  5542. },
  5543. get count () {
  5544. return this.array.length / this.stride;
  5545. },
  5546. set needsUpdate( value ) {
  5547. if ( value === true ) this.version ++;
  5548. },
  5549. setDynamic: function ( value ) {
  5550. this.dynamic = value;
  5551. return this;
  5552. },
  5553. copy: function ( source ) {
  5554. this.array = new source.array.constructor( source.array );
  5555. this.stride = source.stride;
  5556. this.dynamic = source.dynamic;
  5557. },
  5558. copyAt: function ( index1, attribute, index2 ) {
  5559. index1 *= this.stride;
  5560. index2 *= attribute.stride;
  5561. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5562. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5563. }
  5564. return this;
  5565. },
  5566. set: function ( value, offset ) {
  5567. if ( offset === undefined ) offset = 0;
  5568. this.array.set( value, offset );
  5569. return this;
  5570. },
  5571. clone: function () {
  5572. return new this.constructor().copy( this );
  5573. }
  5574. };
  5575. // File:src/core/InstancedInterleavedBuffer.js
  5576. /**
  5577. * @author benaadams / https://twitter.com/ben_a_adams
  5578. */
  5579. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5580. THREE.InterleavedBuffer.call( this, array, stride );
  5581. this.meshPerAttribute = meshPerAttribute || 1;
  5582. };
  5583. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5584. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5585. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5586. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5587. this.meshPerAttribute = source.meshPerAttribute;
  5588. return this;
  5589. };
  5590. // File:src/core/InterleavedBufferAttribute.js
  5591. /**
  5592. * @author benaadams / https://twitter.com/ben_a_adams
  5593. */
  5594. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5595. this.uuid = THREE.Math.generateUUID();
  5596. this.data = interleavedBuffer;
  5597. this.itemSize = itemSize;
  5598. this.offset = offset;
  5599. };
  5600. THREE.InterleavedBufferAttribute.prototype = {
  5601. constructor: THREE.InterleavedBufferAttribute,
  5602. get length() {
  5603. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5604. return this.array.length;
  5605. },
  5606. get count() {
  5607. return this.data.array.length / this.data.stride;
  5608. },
  5609. setX: function ( index, x ) {
  5610. this.data.array[ index * this.data.stride + this.offset ] = x;
  5611. return this;
  5612. },
  5613. setY: function ( index, y ) {
  5614. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5615. return this;
  5616. },
  5617. setZ: function ( index, z ) {
  5618. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5619. return this;
  5620. },
  5621. setW: function ( index, w ) {
  5622. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5623. return this;
  5624. },
  5625. getX: function ( index ) {
  5626. return this.data.array[ index * this.data.stride + this.offset ];
  5627. },
  5628. getY: function ( index ) {
  5629. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5630. },
  5631. getZ: function ( index ) {
  5632. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5633. },
  5634. getW: function ( index ) {
  5635. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5636. },
  5637. setXY: function ( index, x, y ) {
  5638. index = index * this.data.stride + this.offset;
  5639. this.data.array[ index + 0 ] = x;
  5640. this.data.array[ index + 1 ] = y;
  5641. return this;
  5642. },
  5643. setXYZ: function ( index, x, y, z ) {
  5644. index = index * this.data.stride + this.offset;
  5645. this.data.array[ index + 0 ] = x;
  5646. this.data.array[ index + 1 ] = y;
  5647. this.data.array[ index + 2 ] = z;
  5648. return this;
  5649. },
  5650. setXYZW: function ( index, x, y, z, w ) {
  5651. index = index * this.data.stride + this.offset;
  5652. this.data.array[ index + 0 ] = x;
  5653. this.data.array[ index + 1 ] = y;
  5654. this.data.array[ index + 2 ] = z;
  5655. this.data.array[ index + 3 ] = w;
  5656. return this;
  5657. }
  5658. };
  5659. // File:src/core/Geometry.js
  5660. /**
  5661. * @author mrdoob / http://mrdoob.com/
  5662. * @author kile / http://kile.stravaganza.org/
  5663. * @author alteredq / http://alteredqualia.com/
  5664. * @author mikael emtinger / http://gomo.se/
  5665. * @author zz85 / http://www.lab4games.net/zz85/blog
  5666. * @author bhouston / http://clara.io
  5667. */
  5668. THREE.Geometry = function () {
  5669. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5670. this.uuid = THREE.Math.generateUUID();
  5671. this.name = '';
  5672. this.type = 'Geometry';
  5673. this.vertices = [];
  5674. this.colors = [];
  5675. this.faces = [];
  5676. this.faceVertexUvs = [ [] ];
  5677. this.morphTargets = [];
  5678. this.morphNormals = [];
  5679. this.skinWeights = [];
  5680. this.skinIndices = [];
  5681. this.lineDistances = [];
  5682. this.boundingBox = null;
  5683. this.boundingSphere = null;
  5684. // update flags
  5685. this.verticesNeedUpdate = false;
  5686. this.elementsNeedUpdate = false;
  5687. this.uvsNeedUpdate = false;
  5688. this.normalsNeedUpdate = false;
  5689. this.colorsNeedUpdate = false;
  5690. this.lineDistancesNeedUpdate = false;
  5691. this.groupsNeedUpdate = false;
  5692. };
  5693. THREE.Geometry.prototype = {
  5694. constructor: THREE.Geometry,
  5695. applyMatrix: function ( matrix ) {
  5696. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5697. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5698. var vertex = this.vertices[ i ];
  5699. vertex.applyMatrix4( matrix );
  5700. }
  5701. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5702. var face = this.faces[ i ];
  5703. face.normal.applyMatrix3( normalMatrix ).normalize();
  5704. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5705. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5706. }
  5707. }
  5708. if ( this.boundingBox !== null ) {
  5709. this.computeBoundingBox();
  5710. }
  5711. if ( this.boundingSphere !== null ) {
  5712. this.computeBoundingSphere();
  5713. }
  5714. this.verticesNeedUpdate = true;
  5715. this.normalsNeedUpdate = true;
  5716. },
  5717. rotateX: function () {
  5718. // rotate geometry around world x-axis
  5719. var m1;
  5720. return function rotateX( angle ) {
  5721. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5722. m1.makeRotationX( angle );
  5723. this.applyMatrix( m1 );
  5724. return this;
  5725. };
  5726. }(),
  5727. rotateY: function () {
  5728. // rotate geometry around world y-axis
  5729. var m1;
  5730. return function rotateY( angle ) {
  5731. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5732. m1.makeRotationY( angle );
  5733. this.applyMatrix( m1 );
  5734. return this;
  5735. };
  5736. }(),
  5737. rotateZ: function () {
  5738. // rotate geometry around world z-axis
  5739. var m1;
  5740. return function rotateZ( angle ) {
  5741. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5742. m1.makeRotationZ( angle );
  5743. this.applyMatrix( m1 );
  5744. return this;
  5745. };
  5746. }(),
  5747. translate: function () {
  5748. // translate geometry
  5749. var m1;
  5750. return function translate( x, y, z ) {
  5751. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5752. m1.makeTranslation( x, y, z );
  5753. this.applyMatrix( m1 );
  5754. return this;
  5755. };
  5756. }(),
  5757. scale: function () {
  5758. // scale geometry
  5759. var m1;
  5760. return function scale( x, y, z ) {
  5761. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5762. m1.makeScale( x, y, z );
  5763. this.applyMatrix( m1 );
  5764. return this;
  5765. };
  5766. }(),
  5767. lookAt: function () {
  5768. var obj;
  5769. return function lookAt( vector ) {
  5770. if ( obj === undefined ) obj = new THREE.Object3D();
  5771. obj.lookAt( vector );
  5772. obj.updateMatrix();
  5773. this.applyMatrix( obj.matrix );
  5774. };
  5775. }(),
  5776. fromBufferGeometry: function ( geometry ) {
  5777. var scope = this;
  5778. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5779. var attributes = geometry.attributes;
  5780. var vertices = attributes.position.array;
  5781. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5782. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5783. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5784. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5785. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5786. var tempNormals = [];
  5787. var tempUVs = [];
  5788. var tempUVs2 = [];
  5789. for ( var i = 0, j = 0, k = 0; i < vertices.length; i += 3, j += 2, k += 4 ) {
  5790. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5791. if ( normals !== undefined ) {
  5792. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5793. }
  5794. if ( colors !== undefined ) {
  5795. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5796. }
  5797. if ( uvs !== undefined ) {
  5798. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5799. }
  5800. if ( uvs2 !== undefined ) {
  5801. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5802. }
  5803. }
  5804. function addFace( a, b, c ) {
  5805. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5806. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5807. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5808. scope.faces.push( face );
  5809. if ( uvs !== undefined ) {
  5810. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5811. }
  5812. if ( uvs2 !== undefined ) {
  5813. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5814. }
  5815. };
  5816. if ( indices !== undefined ) {
  5817. var groups = geometry.groups;
  5818. if ( groups.length > 0 ) {
  5819. for ( var i = 0; i < groups.length; i ++ ) {
  5820. var group = groups[ i ];
  5821. var start = group.start;
  5822. var count = group.count;
  5823. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5824. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] );
  5825. }
  5826. }
  5827. } else {
  5828. for ( var i = 0; i < indices.length; i += 3 ) {
  5829. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5830. }
  5831. }
  5832. } else {
  5833. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5834. addFace( i, i + 1, i + 2 );
  5835. }
  5836. }
  5837. this.computeFaceNormals();
  5838. if ( geometry.boundingBox !== null ) {
  5839. this.boundingBox = geometry.boundingBox.clone();
  5840. }
  5841. if ( geometry.boundingSphere !== null ) {
  5842. this.boundingSphere = geometry.boundingSphere.clone();
  5843. }
  5844. return this;
  5845. },
  5846. center: function () {
  5847. this.computeBoundingBox();
  5848. var offset = this.boundingBox.center().negate();
  5849. this.translate( offset.x, offset.y, offset.z );
  5850. return offset;
  5851. },
  5852. normalize: function () {
  5853. this.computeBoundingSphere();
  5854. var center = this.boundingSphere.center;
  5855. var radius = this.boundingSphere.radius;
  5856. var s = radius === 0 ? 1 : 1.0 / radius;
  5857. var matrix = new THREE.Matrix4();
  5858. matrix.set(
  5859. s, 0, 0, - s * center.x,
  5860. 0, s, 0, - s * center.y,
  5861. 0, 0, s, - s * center.z,
  5862. 0, 0, 0, 1
  5863. );
  5864. this.applyMatrix( matrix );
  5865. return this;
  5866. },
  5867. computeFaceNormals: function () {
  5868. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5869. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5870. var face = this.faces[ f ];
  5871. var vA = this.vertices[ face.a ];
  5872. var vB = this.vertices[ face.b ];
  5873. var vC = this.vertices[ face.c ];
  5874. cb.subVectors( vC, vB );
  5875. ab.subVectors( vA, vB );
  5876. cb.cross( ab );
  5877. cb.normalize();
  5878. face.normal.copy( cb );
  5879. }
  5880. },
  5881. computeVertexNormals: function ( areaWeighted ) {
  5882. var v, vl, f, fl, face, vertices;
  5883. vertices = new Array( this.vertices.length );
  5884. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5885. vertices[ v ] = new THREE.Vector3();
  5886. }
  5887. if ( areaWeighted ) {
  5888. // vertex normals weighted by triangle areas
  5889. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5890. var vA, vB, vC;
  5891. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5892. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5893. face = this.faces[ f ];
  5894. vA = this.vertices[ face.a ];
  5895. vB = this.vertices[ face.b ];
  5896. vC = this.vertices[ face.c ];
  5897. cb.subVectors( vC, vB );
  5898. ab.subVectors( vA, vB );
  5899. cb.cross( ab );
  5900. vertices[ face.a ].add( cb );
  5901. vertices[ face.b ].add( cb );
  5902. vertices[ face.c ].add( cb );
  5903. }
  5904. } else {
  5905. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5906. face = this.faces[ f ];
  5907. vertices[ face.a ].add( face.normal );
  5908. vertices[ face.b ].add( face.normal );
  5909. vertices[ face.c ].add( face.normal );
  5910. }
  5911. }
  5912. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5913. vertices[ v ].normalize();
  5914. }
  5915. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5916. face = this.faces[ f ];
  5917. var vertexNormals = face.vertexNormals;
  5918. if ( vertexNormals.length === 3 ) {
  5919. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5920. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5921. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5922. } else {
  5923. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5924. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5925. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5926. }
  5927. }
  5928. },
  5929. computeMorphNormals: function () {
  5930. var i, il, f, fl, face;
  5931. // save original normals
  5932. // - create temp variables on first access
  5933. // otherwise just copy (for faster repeated calls)
  5934. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5935. face = this.faces[ f ];
  5936. if ( ! face.__originalFaceNormal ) {
  5937. face.__originalFaceNormal = face.normal.clone();
  5938. } else {
  5939. face.__originalFaceNormal.copy( face.normal );
  5940. }
  5941. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5942. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5943. if ( ! face.__originalVertexNormals[ i ] ) {
  5944. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5945. } else {
  5946. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5947. }
  5948. }
  5949. }
  5950. // use temp geometry to compute face and vertex normals for each morph
  5951. var tmpGeo = new THREE.Geometry();
  5952. tmpGeo.faces = this.faces;
  5953. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5954. // create on first access
  5955. if ( ! this.morphNormals[ i ] ) {
  5956. this.morphNormals[ i ] = {};
  5957. this.morphNormals[ i ].faceNormals = [];
  5958. this.morphNormals[ i ].vertexNormals = [];
  5959. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5960. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5961. var faceNormal, vertexNormals;
  5962. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5963. faceNormal = new THREE.Vector3();
  5964. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5965. dstNormalsFace.push( faceNormal );
  5966. dstNormalsVertex.push( vertexNormals );
  5967. }
  5968. }
  5969. var morphNormals = this.morphNormals[ i ];
  5970. // set vertices to morph target
  5971. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5972. // compute morph normals
  5973. tmpGeo.computeFaceNormals();
  5974. tmpGeo.computeVertexNormals();
  5975. // store morph normals
  5976. var faceNormal, vertexNormals;
  5977. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5978. face = this.faces[ f ];
  5979. faceNormal = morphNormals.faceNormals[ f ];
  5980. vertexNormals = morphNormals.vertexNormals[ f ];
  5981. faceNormal.copy( face.normal );
  5982. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5983. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5984. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5985. }
  5986. }
  5987. // restore original normals
  5988. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5989. face = this.faces[ f ];
  5990. face.normal = face.__originalFaceNormal;
  5991. face.vertexNormals = face.__originalVertexNormals;
  5992. }
  5993. },
  5994. computeTangents: function () {
  5995. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  5996. },
  5997. computeLineDistances: function () {
  5998. var d = 0;
  5999. var vertices = this.vertices;
  6000. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6001. if ( i > 0 ) {
  6002. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6003. }
  6004. this.lineDistances[ i ] = d;
  6005. }
  6006. },
  6007. computeBoundingBox: function () {
  6008. if ( this.boundingBox === null ) {
  6009. this.boundingBox = new THREE.Box3();
  6010. }
  6011. this.boundingBox.setFromPoints( this.vertices );
  6012. },
  6013. computeBoundingSphere: function () {
  6014. if ( this.boundingSphere === null ) {
  6015. this.boundingSphere = new THREE.Sphere();
  6016. }
  6017. this.boundingSphere.setFromPoints( this.vertices );
  6018. },
  6019. merge: function ( geometry, matrix, materialIndexOffset ) {
  6020. if ( geometry instanceof THREE.Geometry === false ) {
  6021. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6022. return;
  6023. }
  6024. var normalMatrix,
  6025. vertexOffset = this.vertices.length,
  6026. vertices1 = this.vertices,
  6027. vertices2 = geometry.vertices,
  6028. faces1 = this.faces,
  6029. faces2 = geometry.faces,
  6030. uvs1 = this.faceVertexUvs[ 0 ],
  6031. uvs2 = geometry.faceVertexUvs[ 0 ];
  6032. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6033. if ( matrix !== undefined ) {
  6034. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6035. }
  6036. // vertices
  6037. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6038. var vertex = vertices2[ i ];
  6039. var vertexCopy = vertex.clone();
  6040. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6041. vertices1.push( vertexCopy );
  6042. }
  6043. // faces
  6044. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6045. var face = faces2[ i ], faceCopy, normal, color,
  6046. faceVertexNormals = face.vertexNormals,
  6047. faceVertexColors = face.vertexColors;
  6048. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6049. faceCopy.normal.copy( face.normal );
  6050. if ( normalMatrix !== undefined ) {
  6051. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6052. }
  6053. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6054. normal = faceVertexNormals[ j ].clone();
  6055. if ( normalMatrix !== undefined ) {
  6056. normal.applyMatrix3( normalMatrix ).normalize();
  6057. }
  6058. faceCopy.vertexNormals.push( normal );
  6059. }
  6060. faceCopy.color.copy( face.color );
  6061. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6062. color = faceVertexColors[ j ];
  6063. faceCopy.vertexColors.push( color.clone() );
  6064. }
  6065. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6066. faces1.push( faceCopy );
  6067. }
  6068. // uvs
  6069. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6070. var uv = uvs2[ i ], uvCopy = [];
  6071. if ( uv === undefined ) {
  6072. continue;
  6073. }
  6074. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6075. uvCopy.push( uv[ j ].clone() );
  6076. }
  6077. uvs1.push( uvCopy );
  6078. }
  6079. },
  6080. mergeMesh: function ( mesh ) {
  6081. if ( mesh instanceof THREE.Mesh === false ) {
  6082. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6083. return;
  6084. }
  6085. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6086. this.merge( mesh.geometry, mesh.matrix );
  6087. },
  6088. /*
  6089. * Checks for duplicate vertices with hashmap.
  6090. * Duplicated vertices are removed
  6091. * and faces' vertices are updated.
  6092. */
  6093. mergeVertices: function () {
  6094. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6095. var unique = [], changes = [];
  6096. var v, key;
  6097. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6098. var precision = Math.pow( 10, precisionPoints );
  6099. var i, il, face;
  6100. var indices, j, jl;
  6101. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6102. v = this.vertices[ i ];
  6103. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6104. if ( verticesMap[ key ] === undefined ) {
  6105. verticesMap[ key ] = i;
  6106. unique.push( this.vertices[ i ] );
  6107. changes[ i ] = unique.length - 1;
  6108. } else {
  6109. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6110. changes[ i ] = changes[ verticesMap[ key ] ];
  6111. }
  6112. }
  6113. // if faces are completely degenerate after merging vertices, we
  6114. // have to remove them from the geometry.
  6115. var faceIndicesToRemove = [];
  6116. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6117. face = this.faces[ i ];
  6118. face.a = changes[ face.a ];
  6119. face.b = changes[ face.b ];
  6120. face.c = changes[ face.c ];
  6121. indices = [ face.a, face.b, face.c ];
  6122. var dupIndex = - 1;
  6123. // if any duplicate vertices are found in a Face3
  6124. // we have to remove the face as nothing can be saved
  6125. for ( var n = 0; n < 3; n ++ ) {
  6126. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6127. dupIndex = n;
  6128. faceIndicesToRemove.push( i );
  6129. break;
  6130. }
  6131. }
  6132. }
  6133. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6134. var idx = faceIndicesToRemove[ i ];
  6135. this.faces.splice( idx, 1 );
  6136. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6137. this.faceVertexUvs[ j ].splice( idx, 1 );
  6138. }
  6139. }
  6140. // Use unique set of vertices
  6141. var diff = this.vertices.length - unique.length;
  6142. this.vertices = unique;
  6143. return diff;
  6144. },
  6145. sortFacesByMaterialIndex: function () {
  6146. var faces = this.faces;
  6147. var length = faces.length;
  6148. // tag faces
  6149. for ( var i = 0; i < length; i ++ ) {
  6150. faces[ i ]._id = i;
  6151. }
  6152. // sort faces
  6153. function materialIndexSort( a, b ) {
  6154. return a.materialIndex - b.materialIndex;
  6155. }
  6156. faces.sort( materialIndexSort );
  6157. // sort uvs
  6158. var uvs1 = this.faceVertexUvs[ 0 ];
  6159. var uvs2 = this.faceVertexUvs[ 1 ];
  6160. var newUvs1, newUvs2;
  6161. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6162. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6163. for ( var i = 0; i < length; i ++ ) {
  6164. var id = faces[ i ]._id;
  6165. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6166. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6167. }
  6168. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6169. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6170. },
  6171. toJSON: function () {
  6172. var data = {
  6173. metadata: {
  6174. version: 4.4,
  6175. type: 'Geometry',
  6176. generator: 'Geometry.toJSON'
  6177. }
  6178. };
  6179. // standard Geometry serialization
  6180. data.uuid = this.uuid;
  6181. data.type = this.type;
  6182. if ( this.name !== '' ) data.name = this.name;
  6183. if ( this.parameters !== undefined ) {
  6184. var parameters = this.parameters;
  6185. for ( var key in parameters ) {
  6186. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6187. }
  6188. return data;
  6189. }
  6190. var vertices = [];
  6191. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6192. var vertex = this.vertices[ i ];
  6193. vertices.push( vertex.x, vertex.y, vertex.z );
  6194. }
  6195. var faces = [];
  6196. var normals = [];
  6197. var normalsHash = {};
  6198. var colors = [];
  6199. var colorsHash = {};
  6200. var uvs = [];
  6201. var uvsHash = {};
  6202. for ( var i = 0; i < this.faces.length; i ++ ) {
  6203. var face = this.faces[ i ];
  6204. var hasMaterial = true;
  6205. var hasFaceUv = false; // deprecated
  6206. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6207. var hasFaceNormal = face.normal.length() > 0;
  6208. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6209. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6210. var hasFaceVertexColor = face.vertexColors.length > 0;
  6211. var faceType = 0;
  6212. faceType = setBit( faceType, 0, 0 ); // isQuad
  6213. faceType = setBit( faceType, 1, hasMaterial );
  6214. faceType = setBit( faceType, 2, hasFaceUv );
  6215. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6216. faceType = setBit( faceType, 4, hasFaceNormal );
  6217. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6218. faceType = setBit( faceType, 6, hasFaceColor );
  6219. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6220. faces.push( faceType );
  6221. faces.push( face.a, face.b, face.c );
  6222. faces.push( face.materialIndex );
  6223. if ( hasFaceVertexUv ) {
  6224. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6225. faces.push(
  6226. getUvIndex( faceVertexUvs[ 0 ] ),
  6227. getUvIndex( faceVertexUvs[ 1 ] ),
  6228. getUvIndex( faceVertexUvs[ 2 ] )
  6229. );
  6230. }
  6231. if ( hasFaceNormal ) {
  6232. faces.push( getNormalIndex( face.normal ) );
  6233. }
  6234. if ( hasFaceVertexNormal ) {
  6235. var vertexNormals = face.vertexNormals;
  6236. faces.push(
  6237. getNormalIndex( vertexNormals[ 0 ] ),
  6238. getNormalIndex( vertexNormals[ 1 ] ),
  6239. getNormalIndex( vertexNormals[ 2 ] )
  6240. );
  6241. }
  6242. if ( hasFaceColor ) {
  6243. faces.push( getColorIndex( face.color ) );
  6244. }
  6245. if ( hasFaceVertexColor ) {
  6246. var vertexColors = face.vertexColors;
  6247. faces.push(
  6248. getColorIndex( vertexColors[ 0 ] ),
  6249. getColorIndex( vertexColors[ 1 ] ),
  6250. getColorIndex( vertexColors[ 2 ] )
  6251. );
  6252. }
  6253. }
  6254. function setBit( value, position, enabled ) {
  6255. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6256. }
  6257. function getNormalIndex( normal ) {
  6258. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6259. if ( normalsHash[ hash ] !== undefined ) {
  6260. return normalsHash[ hash ];
  6261. }
  6262. normalsHash[ hash ] = normals.length / 3;
  6263. normals.push( normal.x, normal.y, normal.z );
  6264. return normalsHash[ hash ];
  6265. }
  6266. function getColorIndex( color ) {
  6267. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6268. if ( colorsHash[ hash ] !== undefined ) {
  6269. return colorsHash[ hash ];
  6270. }
  6271. colorsHash[ hash ] = colors.length;
  6272. colors.push( color.getHex() );
  6273. return colorsHash[ hash ];
  6274. }
  6275. function getUvIndex( uv ) {
  6276. var hash = uv.x.toString() + uv.y.toString();
  6277. if ( uvsHash[ hash ] !== undefined ) {
  6278. return uvsHash[ hash ];
  6279. }
  6280. uvsHash[ hash ] = uvs.length / 2;
  6281. uvs.push( uv.x, uv.y );
  6282. return uvsHash[ hash ];
  6283. }
  6284. data.data = {};
  6285. data.data.vertices = vertices;
  6286. data.data.normals = normals;
  6287. if ( colors.length > 0 ) data.data.colors = colors;
  6288. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6289. data.data.faces = faces;
  6290. return data;
  6291. },
  6292. clone: function () {
  6293. /*
  6294. // Handle primitives
  6295. var parameters = this.parameters;
  6296. if ( parameters !== undefined ) {
  6297. var values = [];
  6298. for ( var key in parameters ) {
  6299. values.push( parameters[ key ] );
  6300. }
  6301. var geometry = Object.create( this.constructor.prototype );
  6302. this.constructor.apply( geometry, values );
  6303. return geometry;
  6304. }
  6305. return new this.constructor().copy( this );
  6306. */
  6307. return new THREE.Geometry().copy( this );
  6308. },
  6309. copy: function ( source ) {
  6310. this.vertices = [];
  6311. this.faces = [];
  6312. this.faceVertexUvs = [ [] ];
  6313. var vertices = source.vertices;
  6314. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6315. this.vertices.push( vertices[ i ].clone() );
  6316. }
  6317. var faces = source.faces;
  6318. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6319. this.faces.push( faces[ i ].clone() );
  6320. }
  6321. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6322. var faceVertexUvs = source.faceVertexUvs[ i ];
  6323. if ( this.faceVertexUvs[ i ] === undefined ) {
  6324. this.faceVertexUvs[ i ] = [];
  6325. }
  6326. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6327. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6328. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6329. var uv = uvs[ k ];
  6330. uvsCopy.push( uv.clone() );
  6331. }
  6332. this.faceVertexUvs[ i ].push( uvsCopy );
  6333. }
  6334. }
  6335. return this;
  6336. },
  6337. dispose: function () {
  6338. this.dispatchEvent( { type: 'dispose' } );
  6339. }
  6340. };
  6341. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6342. THREE.GeometryIdCount = 0;
  6343. // File:src/core/DirectGeometry.js
  6344. /**
  6345. * @author mrdoob / http://mrdoob.com/
  6346. */
  6347. THREE.DirectGeometry = function () {
  6348. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6349. this.uuid = THREE.Math.generateUUID();
  6350. this.name = '';
  6351. this.type = 'DirectGeometry';
  6352. this.indices = [];
  6353. this.vertices = [];
  6354. this.normals = [];
  6355. this.colors = [];
  6356. this.uvs = [];
  6357. this.uvs2 = [];
  6358. this.groups = [];
  6359. this.morphTargets = {};
  6360. this.skinWeights = [];
  6361. this.skinIndices = [];
  6362. // this.lineDistances = [];
  6363. this.boundingBox = null;
  6364. this.boundingSphere = null;
  6365. // update flags
  6366. this.verticesNeedUpdate = false;
  6367. this.normalsNeedUpdate = false;
  6368. this.colorsNeedUpdate = false;
  6369. this.uvsNeedUpdate = false;
  6370. this.groupsNeedUpdate = false;
  6371. };
  6372. THREE.DirectGeometry.prototype = {
  6373. constructor: THREE.DirectGeometry,
  6374. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6375. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6376. computeFaceNormals: function () {
  6377. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6378. },
  6379. computeVertexNormals: function () {
  6380. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6381. },
  6382. computeGroups: function ( geometry ) {
  6383. var group;
  6384. var groups = [];
  6385. var materialIndex;
  6386. var faces = geometry.faces;
  6387. for ( var i = 0; i < faces.length; i ++ ) {
  6388. var face = faces[ i ];
  6389. // materials
  6390. if ( face.materialIndex !== materialIndex ) {
  6391. materialIndex = face.materialIndex;
  6392. if ( group !== undefined ) {
  6393. group.count = ( i * 3 ) - group.start;
  6394. groups.push( group );
  6395. }
  6396. group = {
  6397. start: i * 3,
  6398. materialIndex: materialIndex
  6399. };
  6400. }
  6401. }
  6402. if ( group !== undefined ) {
  6403. group.count = ( i * 3 ) - group.start;
  6404. groups.push( group );
  6405. }
  6406. this.groups = groups;
  6407. },
  6408. fromGeometry: function ( geometry ) {
  6409. var faces = geometry.faces;
  6410. var vertices = geometry.vertices;
  6411. var faceVertexUvs = geometry.faceVertexUvs;
  6412. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6413. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6414. // morphs
  6415. var morphTargets = geometry.morphTargets;
  6416. var morphTargetsLength = morphTargets.length;
  6417. if ( morphTargetsLength > 0 ) {
  6418. var morphTargetsPosition = [];
  6419. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6420. morphTargetsPosition[ i ] = [];
  6421. }
  6422. this.morphTargets.position = morphTargetsPosition;
  6423. }
  6424. var morphNormals = geometry.morphNormals;
  6425. var morphNormalsLength = morphNormals.length;
  6426. if ( morphNormalsLength > 0 ) {
  6427. var morphTargetsNormal = [];
  6428. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6429. morphTargetsNormal[ i ] = [];
  6430. }
  6431. this.morphTargets.normal = morphTargetsNormal;
  6432. }
  6433. // skins
  6434. var skinIndices = geometry.skinIndices;
  6435. var skinWeights = geometry.skinWeights;
  6436. var hasSkinIndices = skinIndices.length === vertices.length;
  6437. var hasSkinWeights = skinWeights.length === vertices.length;
  6438. //
  6439. for ( var i = 0; i < faces.length; i ++ ) {
  6440. var face = faces[ i ];
  6441. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6442. var vertexNormals = face.vertexNormals;
  6443. if ( vertexNormals.length === 3 ) {
  6444. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6445. } else {
  6446. var normal = face.normal;
  6447. this.normals.push( normal, normal, normal );
  6448. }
  6449. var vertexColors = face.vertexColors;
  6450. if ( vertexColors.length === 3 ) {
  6451. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6452. } else {
  6453. var color = face.color;
  6454. this.colors.push( color, color, color );
  6455. }
  6456. if ( hasFaceVertexUv === true ) {
  6457. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6458. if ( vertexUvs !== undefined ) {
  6459. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6460. } else {
  6461. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6462. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6463. }
  6464. }
  6465. if ( hasFaceVertexUv2 === true ) {
  6466. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6467. if ( vertexUvs !== undefined ) {
  6468. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6469. } else {
  6470. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6471. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6472. }
  6473. }
  6474. // morphs
  6475. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6476. var morphTarget = morphTargets[ j ].vertices;
  6477. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6478. }
  6479. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6480. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6481. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6482. }
  6483. // skins
  6484. if ( hasSkinIndices ) {
  6485. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6486. }
  6487. if ( hasSkinWeights ) {
  6488. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6489. }
  6490. }
  6491. this.computeGroups( geometry );
  6492. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6493. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6494. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6495. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6496. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6497. return this;
  6498. },
  6499. dispose: function () {
  6500. this.dispatchEvent( { type: 'dispose' } );
  6501. }
  6502. };
  6503. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6504. // File:src/core/BufferGeometry.js
  6505. /**
  6506. * @author alteredq / http://alteredqualia.com/
  6507. * @author mrdoob / http://mrdoob.com/
  6508. */
  6509. THREE.BufferGeometry = function () {
  6510. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6511. this.uuid = THREE.Math.generateUUID();
  6512. this.name = '';
  6513. this.type = 'BufferGeometry';
  6514. this.index = null;
  6515. this.attributes = {};
  6516. this.morphAttributes = {};
  6517. this.groups = [];
  6518. this.boundingBox = null;
  6519. this.boundingSphere = null;
  6520. this.drawRange = { start: 0, count: Infinity };
  6521. };
  6522. THREE.BufferGeometry.prototype = {
  6523. constructor: THREE.BufferGeometry,
  6524. addIndex: function ( index ) {
  6525. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  6526. this.setIndex( index );
  6527. },
  6528. getIndex: function () {
  6529. return this.index;
  6530. },
  6531. setIndex: function ( index ) {
  6532. this.index = index;
  6533. },
  6534. addAttribute: function ( name, attribute ) {
  6535. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6536. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6537. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6538. return;
  6539. }
  6540. if ( name === 'index' ) {
  6541. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6542. this.setIndex( attribute );
  6543. return;
  6544. }
  6545. this.attributes[ name ] = attribute;
  6546. },
  6547. getAttribute: function ( name ) {
  6548. return this.attributes[ name ];
  6549. },
  6550. removeAttribute: function ( name ) {
  6551. delete this.attributes[ name ];
  6552. },
  6553. get drawcalls() {
  6554. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  6555. return this.groups;
  6556. },
  6557. get offsets() {
  6558. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  6559. return this.groups;
  6560. },
  6561. addDrawCall: function ( start, count, indexOffset ) {
  6562. if ( indexOffset !== undefined ) {
  6563. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  6564. }
  6565. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  6566. this.addGroup( start, count );
  6567. },
  6568. clearDrawCalls: function () {
  6569. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  6570. this.clearGroups();
  6571. },
  6572. addGroup: function ( start, count, materialIndex ) {
  6573. this.groups.push( {
  6574. start: start,
  6575. count: count,
  6576. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6577. } );
  6578. },
  6579. clearGroups: function () {
  6580. this.groups = [];
  6581. },
  6582. setDrawRange: function ( start, count ) {
  6583. this.drawRange.start = start;
  6584. this.drawRange.count = count;
  6585. },
  6586. applyMatrix: function ( matrix ) {
  6587. var position = this.attributes.position;
  6588. if ( position !== undefined ) {
  6589. matrix.applyToVector3Array( position.array );
  6590. position.needsUpdate = true;
  6591. }
  6592. var normal = this.attributes.normal;
  6593. if ( normal !== undefined ) {
  6594. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6595. normalMatrix.applyToVector3Array( normal.array );
  6596. normal.needsUpdate = true;
  6597. }
  6598. if ( this.boundingBox !== null ) {
  6599. this.computeBoundingBox();
  6600. }
  6601. if ( this.boundingSphere !== null ) {
  6602. this.computeBoundingSphere();
  6603. }
  6604. },
  6605. rotateX: function () {
  6606. // rotate geometry around world x-axis
  6607. var m1;
  6608. return function rotateX( angle ) {
  6609. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6610. m1.makeRotationX( angle );
  6611. this.applyMatrix( m1 );
  6612. return this;
  6613. };
  6614. }(),
  6615. rotateY: function () {
  6616. // rotate geometry around world y-axis
  6617. var m1;
  6618. return function rotateY( angle ) {
  6619. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6620. m1.makeRotationY( angle );
  6621. this.applyMatrix( m1 );
  6622. return this;
  6623. };
  6624. }(),
  6625. rotateZ: function () {
  6626. // rotate geometry around world z-axis
  6627. var m1;
  6628. return function rotateZ( angle ) {
  6629. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6630. m1.makeRotationZ( angle );
  6631. this.applyMatrix( m1 );
  6632. return this;
  6633. };
  6634. }(),
  6635. translate: function () {
  6636. // translate geometry
  6637. var m1;
  6638. return function translate( x, y, z ) {
  6639. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6640. m1.makeTranslation( x, y, z );
  6641. this.applyMatrix( m1 );
  6642. return this;
  6643. };
  6644. }(),
  6645. scale: function () {
  6646. // scale geometry
  6647. var m1;
  6648. return function scale( x, y, z ) {
  6649. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6650. m1.makeScale( x, y, z );
  6651. this.applyMatrix( m1 );
  6652. return this;
  6653. };
  6654. }(),
  6655. lookAt: function () {
  6656. var obj;
  6657. return function lookAt( vector ) {
  6658. if ( obj === undefined ) obj = new THREE.Object3D();
  6659. obj.lookAt( vector );
  6660. obj.updateMatrix();
  6661. this.applyMatrix( obj.matrix );
  6662. };
  6663. }(),
  6664. center: function () {
  6665. this.computeBoundingBox();
  6666. var offset = this.boundingBox.center().negate();
  6667. this.translate( offset.x, offset.y, offset.z );
  6668. return offset;
  6669. },
  6670. setFromObject: function ( object ) {
  6671. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6672. var geometry = object.geometry;
  6673. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6674. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6675. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6676. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6677. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6678. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6679. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6680. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6681. }
  6682. if ( geometry.boundingSphere !== null ) {
  6683. this.boundingSphere = geometry.boundingSphere.clone();
  6684. }
  6685. if ( geometry.boundingBox !== null ) {
  6686. this.boundingBox = geometry.boundingBox.clone();
  6687. }
  6688. } else if ( object instanceof THREE.Mesh ) {
  6689. if ( geometry instanceof THREE.Geometry ) {
  6690. this.fromGeometry( geometry );
  6691. }
  6692. }
  6693. return this;
  6694. },
  6695. updateFromObject: function ( object ) {
  6696. var geometry = object.geometry;
  6697. if ( object instanceof THREE.Mesh ) {
  6698. var direct = geometry.__directGeometry;
  6699. if ( direct === undefined ) {
  6700. return this.fromGeometry( geometry );
  6701. }
  6702. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6703. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6704. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6705. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6706. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6707. geometry.verticesNeedUpdate = false;
  6708. geometry.normalsNeedUpdate = false;
  6709. geometry.colorsNeedUpdate = false;
  6710. geometry.uvsNeedUpdate = false;
  6711. geometry.groupsNeedUpdate = false;
  6712. geometry = direct;
  6713. }
  6714. if ( geometry.verticesNeedUpdate === true ) {
  6715. var attribute = this.attributes.position;
  6716. if ( attribute !== undefined ) {
  6717. attribute.copyVector3sArray( geometry.vertices );
  6718. attribute.needsUpdate = true;
  6719. }
  6720. geometry.verticesNeedUpdate = false;
  6721. }
  6722. if ( geometry.normalsNeedUpdate === true ) {
  6723. var attribute = this.attributes.normal;
  6724. if ( attribute !== undefined ) {
  6725. attribute.copyVector3sArray( geometry.normals );
  6726. attribute.needsUpdate = true;
  6727. }
  6728. geometry.normalsNeedUpdate = false;
  6729. }
  6730. if ( geometry.colorsNeedUpdate === true ) {
  6731. var attribute = this.attributes.color;
  6732. if ( attribute !== undefined ) {
  6733. attribute.copyColorsArray( geometry.colors );
  6734. attribute.needsUpdate = true;
  6735. }
  6736. geometry.colorsNeedUpdate = false;
  6737. }
  6738. if ( geometry.uvsNeedUpdate ) {
  6739. var attribute = this.attributes.uv;
  6740. if ( attribute !== undefined ) {
  6741. attribute.copyVector2sArray( geometry.uvs );
  6742. attribute.needsUpdate = true;
  6743. }
  6744. geometry.uvsNeedUpdate = false;
  6745. }
  6746. if ( geometry.lineDistancesNeedUpdate ) {
  6747. var attribute = this.attributes.lineDistance;
  6748. if ( attribute !== undefined ) {
  6749. attribute.copyArray( geometry.lineDistances );
  6750. attribute.needsUpdate = true;
  6751. }
  6752. geometry.lineDistancesNeedUpdate = false;
  6753. }
  6754. if ( geometry.groupsNeedUpdate ) {
  6755. geometry.computeGroups( object.geometry );
  6756. this.groups = geometry.groups;
  6757. geometry.groupsNeedUpdate = false;
  6758. }
  6759. return this;
  6760. },
  6761. fromGeometry: function ( geometry ) {
  6762. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6763. return this.fromDirectGeometry( geometry.__directGeometry );
  6764. },
  6765. fromDirectGeometry: function ( geometry ) {
  6766. var positions = new Float32Array( geometry.vertices.length * 3 );
  6767. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6768. if ( geometry.normals.length > 0 ) {
  6769. var normals = new Float32Array( geometry.normals.length * 3 );
  6770. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6771. }
  6772. if ( geometry.colors.length > 0 ) {
  6773. var colors = new Float32Array( geometry.colors.length * 3 );
  6774. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6775. }
  6776. if ( geometry.uvs.length > 0 ) {
  6777. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6778. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6779. }
  6780. if ( geometry.uvs2.length > 0 ) {
  6781. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6782. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6783. }
  6784. if ( geometry.indices.length > 0 ) {
  6785. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6786. var indices = new TypeArray( geometry.indices.length * 3 );
  6787. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6788. }
  6789. // groups
  6790. this.groups = geometry.groups;
  6791. // morphs
  6792. for ( var name in geometry.morphTargets ) {
  6793. var array = [];
  6794. var morphTargets = geometry.morphTargets[ name ];
  6795. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6796. var morphTarget = morphTargets[ i ];
  6797. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6798. array.push( attribute.copyVector3sArray( morphTarget ) );
  6799. }
  6800. this.morphAttributes[ name ] = array;
  6801. }
  6802. // skinning
  6803. if ( geometry.skinIndices.length > 0 ) {
  6804. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6805. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6806. }
  6807. if ( geometry.skinWeights.length > 0 ) {
  6808. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6809. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6810. }
  6811. //
  6812. if ( geometry.boundingSphere !== null ) {
  6813. this.boundingSphere = geometry.boundingSphere.clone();
  6814. }
  6815. if ( geometry.boundingBox !== null ) {
  6816. this.boundingBox = geometry.boundingBox.clone();
  6817. }
  6818. return this;
  6819. },
  6820. computeBoundingBox: function () {
  6821. var vector = new THREE.Vector3();
  6822. return function () {
  6823. if ( this.boundingBox === null ) {
  6824. this.boundingBox = new THREE.Box3();
  6825. }
  6826. var positions = this.attributes.position.array;
  6827. if ( positions ) {
  6828. var bb = this.boundingBox;
  6829. bb.makeEmpty();
  6830. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6831. vector.fromArray( positions, i );
  6832. bb.expandByPoint( vector );
  6833. }
  6834. }
  6835. if ( positions === undefined || positions.length === 0 ) {
  6836. this.boundingBox.min.set( 0, 0, 0 );
  6837. this.boundingBox.max.set( 0, 0, 0 );
  6838. }
  6839. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6840. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6841. }
  6842. };
  6843. }(),
  6844. computeBoundingSphere: function () {
  6845. var box = new THREE.Box3();
  6846. var vector = new THREE.Vector3();
  6847. return function () {
  6848. if ( this.boundingSphere === null ) {
  6849. this.boundingSphere = new THREE.Sphere();
  6850. }
  6851. var positions = this.attributes.position.array;
  6852. if ( positions ) {
  6853. box.makeEmpty();
  6854. var center = this.boundingSphere.center;
  6855. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6856. vector.fromArray( positions, i );
  6857. box.expandByPoint( vector );
  6858. }
  6859. box.center( center );
  6860. // hoping to find a boundingSphere with a radius smaller than the
  6861. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6862. var maxRadiusSq = 0;
  6863. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6864. vector.fromArray( positions, i );
  6865. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6866. }
  6867. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6868. if ( isNaN( this.boundingSphere.radius ) ) {
  6869. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6870. }
  6871. }
  6872. };
  6873. }(),
  6874. computeFaceNormals: function () {
  6875. // backwards compatibility
  6876. },
  6877. computeVertexNormals: function () {
  6878. var index = this.index;
  6879. var attributes = this.attributes;
  6880. var groups = this.groups;
  6881. if ( attributes.position ) {
  6882. var positions = attributes.position.array;
  6883. if ( attributes.normal === undefined ) {
  6884. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6885. } else {
  6886. // reset existing normals to zero
  6887. var normals = attributes.normal.array;
  6888. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  6889. normals[ i ] = 0;
  6890. }
  6891. }
  6892. var normals = attributes.normal.array;
  6893. var vA, vB, vC,
  6894. pA = new THREE.Vector3(),
  6895. pB = new THREE.Vector3(),
  6896. pC = new THREE.Vector3(),
  6897. cb = new THREE.Vector3(),
  6898. ab = new THREE.Vector3();
  6899. // indexed elements
  6900. if ( index ) {
  6901. var indices = index.array;
  6902. if ( groups.length === 0 ) {
  6903. this.addGroup( 0, indices.length );
  6904. }
  6905. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  6906. var group = groups[ j ];
  6907. var start = group.start;
  6908. var count = group.count;
  6909. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6910. vA = indices[ i + 0 ] * 3;
  6911. vB = indices[ i + 1 ] * 3;
  6912. vC = indices[ i + 2 ] * 3;
  6913. pA.fromArray( positions, vA );
  6914. pB.fromArray( positions, vB );
  6915. pC.fromArray( positions, vC );
  6916. cb.subVectors( pC, pB );
  6917. ab.subVectors( pA, pB );
  6918. cb.cross( ab );
  6919. normals[ vA ] += cb.x;
  6920. normals[ vA + 1 ] += cb.y;
  6921. normals[ vA + 2 ] += cb.z;
  6922. normals[ vB ] += cb.x;
  6923. normals[ vB + 1 ] += cb.y;
  6924. normals[ vB + 2 ] += cb.z;
  6925. normals[ vC ] += cb.x;
  6926. normals[ vC + 1 ] += cb.y;
  6927. normals[ vC + 2 ] += cb.z;
  6928. }
  6929. }
  6930. } else {
  6931. // non-indexed elements (unconnected triangle soup)
  6932. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6933. pA.fromArray( positions, i );
  6934. pB.fromArray( positions, i + 3 );
  6935. pC.fromArray( positions, i + 6 );
  6936. cb.subVectors( pC, pB );
  6937. ab.subVectors( pA, pB );
  6938. cb.cross( ab );
  6939. normals[ i ] = cb.x;
  6940. normals[ i + 1 ] = cb.y;
  6941. normals[ i + 2 ] = cb.z;
  6942. normals[ i + 3 ] = cb.x;
  6943. normals[ i + 4 ] = cb.y;
  6944. normals[ i + 5 ] = cb.z;
  6945. normals[ i + 6 ] = cb.x;
  6946. normals[ i + 7 ] = cb.y;
  6947. normals[ i + 8 ] = cb.z;
  6948. }
  6949. }
  6950. this.normalizeNormals();
  6951. attributes.normal.needsUpdate = true;
  6952. }
  6953. },
  6954. computeTangents: function () {
  6955. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  6956. },
  6957. computeOffsets: function ( size ) {
  6958. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.');
  6959. },
  6960. merge: function ( geometry, offset ) {
  6961. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6962. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6963. return;
  6964. }
  6965. if ( offset === undefined ) offset = 0;
  6966. var attributes = this.attributes;
  6967. for ( var key in attributes ) {
  6968. if ( geometry.attributes[ key ] === undefined ) continue;
  6969. var attribute1 = attributes[ key ];
  6970. var attributeArray1 = attribute1.array;
  6971. var attribute2 = geometry.attributes[ key ];
  6972. var attributeArray2 = attribute2.array;
  6973. var attributeSize = attribute2.itemSize;
  6974. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6975. attributeArray1[ j ] = attributeArray2[ i ];
  6976. }
  6977. }
  6978. return this;
  6979. },
  6980. normalizeNormals: function () {
  6981. var normals = this.attributes.normal.array;
  6982. var x, y, z, n;
  6983. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6984. x = normals[ i ];
  6985. y = normals[ i + 1 ];
  6986. z = normals[ i + 2 ];
  6987. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6988. normals[ i ] *= n;
  6989. normals[ i + 1 ] *= n;
  6990. normals[ i + 2 ] *= n;
  6991. }
  6992. },
  6993. toJSON: function () {
  6994. var data = {
  6995. metadata: {
  6996. version: 4.4,
  6997. type: 'BufferGeometry',
  6998. generator: 'BufferGeometry.toJSON'
  6999. }
  7000. };
  7001. // standard BufferGeometry serialization
  7002. data.uuid = this.uuid;
  7003. data.type = this.type;
  7004. if ( this.name !== '' ) data.name = this.name;
  7005. if ( this.parameters !== undefined ) {
  7006. var parameters = this.parameters;
  7007. for ( var key in parameters ) {
  7008. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7009. }
  7010. return data;
  7011. }
  7012. data.data = { attributes: {} };
  7013. var index = this.index;
  7014. if ( index !== null ) {
  7015. var array = Array.prototype.slice.call( index.array );
  7016. data.data.index = {
  7017. type: index.array.constructor.name,
  7018. array: array
  7019. };
  7020. }
  7021. var attributes = this.attributes;
  7022. for ( var key in attributes ) {
  7023. var attribute = attributes[ key ];
  7024. var array = Array.prototype.slice.call( attribute.array );
  7025. data.data.attributes[ key ] = {
  7026. itemSize: attribute.itemSize,
  7027. type: attribute.array.constructor.name,
  7028. array: array
  7029. };
  7030. }
  7031. var groups = this.groups;
  7032. if ( groups.length > 0 ) {
  7033. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7034. }
  7035. var boundingSphere = this.boundingSphere;
  7036. if ( boundingSphere !== null ) {
  7037. data.data.boundingSphere = {
  7038. center: boundingSphere.center.toArray(),
  7039. radius: boundingSphere.radius
  7040. };
  7041. }
  7042. return data;
  7043. },
  7044. clone: function () {
  7045. /*
  7046. // Handle primitives
  7047. var parameters = this.parameters;
  7048. if ( parameters !== undefined ) {
  7049. var values = [];
  7050. for ( var key in parameters ) {
  7051. values.push( parameters[ key ] );
  7052. }
  7053. var geometry = Object.create( this.constructor.prototype );
  7054. this.constructor.apply( geometry, values );
  7055. return geometry;
  7056. }
  7057. return new this.constructor().copy( this );
  7058. */
  7059. return new THREE.BufferGeometry().copy( this );
  7060. },
  7061. copy: function ( source ) {
  7062. var index = source.index;
  7063. if ( index !== null ) {
  7064. this.setIndex( index.clone() );
  7065. }
  7066. var attributes = source.attributes;
  7067. for ( var name in attributes ) {
  7068. var attribute = attributes[ name ];
  7069. this.addAttribute( name, attribute.clone() );
  7070. }
  7071. var groups = source.groups;
  7072. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7073. var group = groups[ i ];
  7074. this.addGroup( group.start, group.count );
  7075. }
  7076. return this;
  7077. },
  7078. dispose: function () {
  7079. this.dispatchEvent( { type: 'dispose' } );
  7080. }
  7081. };
  7082. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7083. THREE.BufferGeometry.MaxIndex = 65535;
  7084. // File:src/core/InstancedBufferGeometry.js
  7085. /**
  7086. * @author benaadams / https://twitter.com/ben_a_adams
  7087. */
  7088. THREE.InstancedBufferGeometry = function () {
  7089. THREE.BufferGeometry.call( this );
  7090. this.type = 'InstancedBufferGeometry';
  7091. this.maxInstancedCount = undefined;
  7092. };
  7093. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7094. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7095. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7096. this.groups.push( {
  7097. start: start,
  7098. count: count,
  7099. instances: instances
  7100. } );
  7101. };
  7102. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7103. var index = source.index;
  7104. if ( index !== null ) {
  7105. this.setIndex( index.clone() );
  7106. }
  7107. var attributes = source.attributes;
  7108. for ( var name in attributes ) {
  7109. var attribute = attributes[ name ];
  7110. this.addAttribute( name, attribute.clone() );
  7111. }
  7112. var groups = source.groups;
  7113. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7114. var group = groups[ i ];
  7115. this.addGroup( group.start, group.count, group.instances );
  7116. }
  7117. return this;
  7118. };
  7119. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7120. // File:src/core/Uniform.js
  7121. /**
  7122. * @author mrdoob / http://mrdoob.com/
  7123. */
  7124. THREE.Uniform = function ( type, value ) {
  7125. this.type = type;
  7126. this.value = value;
  7127. this.dynamic = false;
  7128. };
  7129. THREE.Uniform.prototype = {
  7130. constructor: THREE.Uniform,
  7131. onUpdate: function ( callback ) {
  7132. this.dynamic = true;
  7133. this.onUpdateCallback = callback;
  7134. return this;
  7135. }
  7136. };
  7137. // File:src/animation/AnimationClip.js
  7138. /**
  7139. *
  7140. * Reusable set of Tracks that represent an animation.
  7141. *
  7142. * @author Ben Houston / http://clara.io/
  7143. * @author David Sarno / http://lighthaus.us/
  7144. */
  7145. THREE.AnimationClip = function ( name, duration, tracks ) {
  7146. this.name = name || THREE.Math.generateUUID();
  7147. this.tracks = tracks;
  7148. this.duration = ( duration !== undefined ) ? duration : -1;
  7149. // this means it should figure out its duration by scanning the tracks
  7150. if ( this.duration < 0 ) {
  7151. this.resetDuration();
  7152. }
  7153. // maybe only do these on demand, as doing them here could potentially slow down loading
  7154. // but leaving these here during development as this ensures a lot of testing of these functions
  7155. this.trim();
  7156. this.optimize();
  7157. };
  7158. THREE.AnimationClip.prototype = {
  7159. constructor: THREE.AnimationClip,
  7160. resetDuration: function() {
  7161. var tracks = this.tracks,
  7162. duration = 0;
  7163. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7164. var track = this.tracks[ i ];
  7165. duration = Math.max(
  7166. duration, track.times[ track.times.length - 1 ] );
  7167. }
  7168. this.duration = duration;
  7169. },
  7170. trim: function() {
  7171. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7172. this.tracks[ i ].trim( 0, this.duration );
  7173. }
  7174. return this;
  7175. },
  7176. optimize: function() {
  7177. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7178. this.tracks[ i ].optimize();
  7179. }
  7180. return this;
  7181. }
  7182. };
  7183. // Static methods:
  7184. Object.assign( THREE.AnimationClip, {
  7185. parse: function( json ) {
  7186. var tracks = [],
  7187. jsonTracks = json.tracks,
  7188. frameTime = 1.0 / ( json.fps || 1.0 );
  7189. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7190. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7191. }
  7192. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7193. },
  7194. toJSON: function( clip ) {
  7195. var tracks = [],
  7196. clipTracks = clip.tracks;
  7197. var json = {
  7198. 'name': clip.name,
  7199. 'duration': clip.duration,
  7200. 'tracks': tracks
  7201. };
  7202. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7203. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7204. }
  7205. return json;
  7206. },
  7207. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps ) {
  7208. var numMorphTargets = morphTargetSequence.length;
  7209. var tracks = [];
  7210. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7211. var times = [];
  7212. var values = [];
  7213. times.push(
  7214. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7215. i,
  7216. ( i + 1 ) % numMorphTargets );
  7217. values.push( 0, 1, 0 );
  7218. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7219. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7220. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7221. // if there is a key at the first frame, duplicate it as the
  7222. // last frame as well for perfect loop.
  7223. if ( times[ 0 ] === 0 ) {
  7224. times.push( numMorphTargets );
  7225. values.push( values[ 0 ] );
  7226. }
  7227. tracks.push(
  7228. new THREE.NumberKeyframeTrack(
  7229. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7230. times, values
  7231. ).scale( 1.0 / fps ) );
  7232. }
  7233. return new THREE.AnimationClip( name, -1, tracks );
  7234. },
  7235. findByName: function( clipArray, name ) {
  7236. for ( var i = 0; i < clipArray.length; i ++ ) {
  7237. if ( clipArray[ i ].name === name ) {
  7238. return clipArray[ i ];
  7239. }
  7240. }
  7241. return null;
  7242. },
  7243. CreateClipsFromMorphTargetSequences: function( morphTargets, fps ) {
  7244. var animationToMorphTargets = {};
  7245. // tested with https://regex101.com/ on trick sequences
  7246. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7247. var pattern = /^([\w-]*?)([\d]+)$/;
  7248. // sort morph target names into animation groups based
  7249. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7250. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7251. var morphTarget = morphTargets[ i ];
  7252. var parts = morphTarget.name.match( pattern );
  7253. if ( parts && parts.length > 1 ) {
  7254. var name = parts[ 1 ];
  7255. var animationMorphTargets = animationToMorphTargets[ name ];
  7256. if ( ! animationMorphTargets ) {
  7257. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7258. }
  7259. animationMorphTargets.push( morphTarget );
  7260. }
  7261. }
  7262. var clips = [];
  7263. for ( var name in animationToMorphTargets ) {
  7264. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7265. }
  7266. return clips;
  7267. },
  7268. // parse the animation.hierarchy format
  7269. parseAnimation: function( animation, bones, nodeName ) {
  7270. if ( ! animation ) {
  7271. console.error( " no animation in JSONLoader data" );
  7272. return null;
  7273. }
  7274. var addNonemptyTrack = function(
  7275. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7276. // only return track if there are actually keys.
  7277. if ( animationKeys.length !== 0 ) {
  7278. var times = [];
  7279. var values = [];
  7280. THREE.AnimationUtils.flattenJSON(
  7281. animationKeys, times, values, propertyName );
  7282. // empty keys are filtered out, so check again
  7283. if ( times.length !== 0 ) {
  7284. destTracks.push( new trackType( trackName, times, values ) );
  7285. }
  7286. }
  7287. };
  7288. var tracks = [];
  7289. var clipName = animation.name || 'default';
  7290. // automatic length determination in AnimationClip.
  7291. var duration = animation.length || -1;
  7292. var fps = animation.fps || 30;
  7293. var hierarchyTracks = animation.hierarchy || [];
  7294. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7295. var animationKeys = hierarchyTracks[ h ].keys;
  7296. // skip empty tracks
  7297. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7298. // process morph targets in a way exactly compatible
  7299. // with AnimationHandler.init( animation )
  7300. if ( animationKeys[0].morphTargets ) {
  7301. // figure out all morph targets used in this track
  7302. var morphTargetNames = {};
  7303. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7304. if ( animationKeys[k].morphTargets ) {
  7305. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7306. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7307. }
  7308. }
  7309. }
  7310. // create a track for each morph target with all zero
  7311. // morphTargetInfluences except for the keys in which
  7312. // the morphTarget is named.
  7313. for ( var morphTargetName in morphTargetNames ) {
  7314. var times = [];
  7315. var values = [];
  7316. for ( var m = 0;
  7317. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7318. var animationKey = animationKeys[k];
  7319. times.push( animationKey.time );
  7320. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7321. }
  7322. tracks.push( new THREE.NumberKeyframeTrack(
  7323. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7324. }
  7325. duration = morphTargetNames.length * ( fps || 1.0 );
  7326. } else {
  7327. // ...assume skeletal animation
  7328. var boneName = '.bones[' + bones[ h ].name + ']';
  7329. addNonemptyTrack(
  7330. THREE.VectorKeyframeTrack, boneName + '.position',
  7331. animationKeys, 'pos', tracks );
  7332. addNonemptyTrack(
  7333. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7334. animationKeys, 'rot', tracks );
  7335. addNonemptyTrack(
  7336. THREE.VectorKeyframeTrack, boneName + '.scale',
  7337. animationKeys, 'scl', tracks );
  7338. }
  7339. }
  7340. if ( tracks.length === 0 ) {
  7341. return null;
  7342. }
  7343. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7344. return clip;
  7345. }
  7346. } );
  7347. // File:src/animation/AnimationMixer.js
  7348. /**
  7349. *
  7350. * Player for AnimationClips.
  7351. *
  7352. *
  7353. * @author Ben Houston / http://clara.io/
  7354. * @author David Sarno / http://lighthaus.us/
  7355. * @author tschw
  7356. */
  7357. THREE.AnimationMixer = function( root ) {
  7358. this._root = root;
  7359. this._initMemoryManager();
  7360. this._accuIndex = 0;
  7361. this.time = 0;
  7362. this.timeScale = 1.0;
  7363. };
  7364. THREE.AnimationMixer.prototype = {
  7365. constructor: THREE.AnimationMixer,
  7366. // return an action for a clip optionally using a custom root target
  7367. // object (this method allocates a lot of dynamic memory in case a
  7368. // previously unknown clip/root combination is specified)
  7369. clipAction: function( clip, optionalRoot ) {
  7370. var root = optionalRoot || this._root,
  7371. rootUuid = root.uuid,
  7372. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7373. clipObject = ( clip !== clipName ) ? clip : null,
  7374. actionsForClip = this._actionsByClip[ clipName ],
  7375. prototypeAction;
  7376. if ( actionsForClip !== undefined ) {
  7377. var existingAction =
  7378. actionsForClip.actionByRoot[ rootUuid ];
  7379. if ( existingAction !== undefined ) {
  7380. return existingAction;
  7381. }
  7382. // we know the clip, so we don't have to parse all
  7383. // the bindings again but can just copy
  7384. prototypeAction = actionsForClip.knownActions[ 0 ];
  7385. // also, take the clip from the prototype action
  7386. clipObject = prototypeAction._clip;
  7387. if ( clip !== clipName && clip !== clipObject ) {
  7388. throw new Error(
  7389. "Different clips with the same name detected!" );
  7390. }
  7391. }
  7392. // clip must be known when specified via string
  7393. if ( clipObject === null ) return null;
  7394. // allocate all resources required to run it
  7395. var newAction = new THREE.
  7396. AnimationMixer._Action( this, clipObject, optionalRoot );
  7397. this._bindAction( newAction, prototypeAction );
  7398. // and make the action known to the memory manager
  7399. this._addInactiveAction( newAction, clipName, rootUuid );
  7400. return newAction;
  7401. },
  7402. // get an existing action
  7403. existingAction: function( clip, optionalRoot ) {
  7404. var root = optionalRoot || this._root,
  7405. rootUuid = root.uuid,
  7406. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7407. actionsForClip = this._actionsByClip[ clipName ];
  7408. if ( actionsForClip !== undefined ) {
  7409. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7410. }
  7411. return null;
  7412. },
  7413. // deactivates all previously scheduled actions
  7414. stopAllAction: function() {
  7415. var actions = this._actions,
  7416. nActions = this._nActiveActions,
  7417. bindings = this._bindings,
  7418. nBindings = this._nActiveBindings;
  7419. this._nActiveActions = 0;
  7420. this._nActiveBindings = 0;
  7421. for ( var i = 0; i !== nActions; ++ i ) {
  7422. actions[ i ].reset();
  7423. }
  7424. for ( var i = 0; i !== nBindings; ++ i ) {
  7425. bindings[ i ].useCount = 0;
  7426. }
  7427. return this;
  7428. },
  7429. // advance the time and update apply the animation
  7430. update: function( deltaTime ) {
  7431. deltaTime *= this.timeScale;
  7432. var actions = this._actions,
  7433. nActions = this._nActiveActions,
  7434. time = this.time += deltaTime,
  7435. timeDirection = Math.sign( deltaTime ),
  7436. accuIndex = this._accuIndex ^= 1;
  7437. // run active actions
  7438. for ( var i = 0; i !== nActions; ++ i ) {
  7439. var action = actions[ i ];
  7440. if ( action.enabled ) {
  7441. action._update( time, deltaTime, timeDirection, accuIndex );
  7442. }
  7443. }
  7444. // update scene graph
  7445. var bindings = this._bindings,
  7446. nBindings = this._nActiveBindings;
  7447. for ( var i = 0; i !== nBindings; ++ i ) {
  7448. bindings[ i ].apply( accuIndex );
  7449. }
  7450. return this;
  7451. },
  7452. // return this mixer's root target object
  7453. getRoot: function() {
  7454. return this._root;
  7455. },
  7456. // free all resources specific to a particular clip
  7457. uncacheClip: function( clip ) {
  7458. var actions = this._actions,
  7459. clipName = clip.name,
  7460. actionsByClip = this._actionsByClip,
  7461. actionsForClip = actionsByClip[ clipName ];
  7462. if ( actionsForClip !== undefined ) {
  7463. // note: just calling _removeInactiveAction would mess up the
  7464. // iteration state and also require updating the state we can
  7465. // just throw away
  7466. var actionsToRemove = actionsForClip.knownActions;
  7467. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7468. var action = actionsToRemove[ i ];
  7469. this._deactivateAction( action );
  7470. var cacheIndex = action._cacheIndex,
  7471. lastInactiveAction = actions[ actions.length - 1 ];
  7472. action._cacheIndex = null;
  7473. action._byClipCacheIndex = null;
  7474. lastInactiveAction._cacheIndex = cacheIndex;
  7475. actions[ cacheIndex ] = lastInactiveAction;
  7476. actions.pop();
  7477. this._removeInactiveBindingsForAction( action );
  7478. }
  7479. delete actionsByClip[ clipName ];
  7480. }
  7481. },
  7482. // free all resources specific to a particular root target object
  7483. uncacheRoot: function( root ) {
  7484. var rootUuid = root.uuid,
  7485. actionsByClip = this._actionsByClip;
  7486. for ( var clipName in actionsByClip ) {
  7487. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7488. action = actionByRoot[ rootUuid ];
  7489. if ( action !== undefined ) {
  7490. this._deactivateAction( action );
  7491. this._removeInactiveAction( action );
  7492. }
  7493. }
  7494. var bindingsByRoot = this._bindingsByRootAndName,
  7495. bindingByName = bindingsByRoot[ rootUuid ];
  7496. if ( bindingByName !== undefined ) {
  7497. for ( var trackName in bindingByName ) {
  7498. var binding = bindingByName[ trackName ];
  7499. binding.restoreOriginalState();
  7500. this._removeInactiveBinding( binding );
  7501. }
  7502. }
  7503. },
  7504. // remove a targeted clip from the cache
  7505. uncacheAction: function( clip, optionalRoot ) {
  7506. var action = this.existingAction( clip, optionalRoot );
  7507. if ( action !== null ) {
  7508. this._deactivateAction( action );
  7509. this._removeInactiveAction( action );
  7510. }
  7511. }
  7512. };
  7513. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7514. THREE.AnimationMixer._Action =
  7515. function( mixer, clip, localRoot ) {
  7516. this._mixer = mixer;
  7517. this._clip = clip;
  7518. this._localRoot = localRoot || null;
  7519. var tracks = clip.tracks,
  7520. nTracks = tracks.length,
  7521. interpolants = new Array( nTracks );
  7522. var interpolantSettings = {
  7523. endingStart: THREE.ZeroCurvatureEnding,
  7524. endingEnd: THREE.ZeroCurvatureEnding
  7525. };
  7526. for ( var i = 0; i !== nTracks; ++ i ) {
  7527. var interpolant = tracks[ i ].createInterpolant( null );
  7528. interpolants[ i ] = interpolant;
  7529. interpolant.settings = interpolantSettings
  7530. }
  7531. this._interpolantSettings = interpolantSettings;
  7532. this._interpolants = interpolants; // bound by the mixer
  7533. // inside: PropertyMixer (managed by the mixer)
  7534. this._propertyBindings = new Array( nTracks );
  7535. this._cacheIndex = null; // for the memory manager
  7536. this._byClipCacheIndex = null; // for the memory manager
  7537. this._timeScaleInterpolant = null;
  7538. this._weightInterpolant = null;
  7539. this.loop = THREE.LoopRepeat;
  7540. this._loopCount = -1;
  7541. // global mixer time when the action is to be started
  7542. // it's set back to 'null' upon start of the action
  7543. this._startTime = null;
  7544. // scaled local time of the action
  7545. // gets clamped or wrapped to 0..clip.duration according to loop
  7546. this.time = 0;
  7547. this.timeScale = 1;
  7548. this._effectiveTimeScale = 1;
  7549. this.weight = 1;
  7550. this._effectiveWeight = 1;
  7551. this.repetitions = Infinity; // no. of repetitions when looping
  7552. this.paused = false; // false -> zero effective time scale
  7553. this.enabled = true; // true -> zero effective weight
  7554. this.clampWhenFinished = false; // keep feeding the last frame?
  7555. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7556. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7557. };
  7558. THREE.AnimationMixer._Action.prototype = {
  7559. constructor: THREE.AnimationMixer._Action,
  7560. // State & Scheduling
  7561. play: function() {
  7562. this._mixer._activateAction( this );
  7563. return this;
  7564. },
  7565. stop: function() {
  7566. this._mixer._deactivateAction( this );
  7567. return this.reset();
  7568. },
  7569. reset: function() {
  7570. this.paused = false;
  7571. this.enabled = true;
  7572. this.time = 0; // restart clip
  7573. this._loopCount = -1; // forget previous loops
  7574. this._startTime = null; // forget scheduling
  7575. return this.stopFading().stopWarping();
  7576. },
  7577. isRunning: function() {
  7578. var start = this._startTime;
  7579. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7580. this._startTime === null && this._mixer._isActiveAction( this )
  7581. },
  7582. // return true when play has been called
  7583. isScheduled: function() {
  7584. return this._mixer._isActiveAction( this );
  7585. },
  7586. startAt: function( time ) {
  7587. this._startTime = time;
  7588. return this;
  7589. },
  7590. setLoop: function( mode, repetitions ) {
  7591. this.loop = mode;
  7592. this.repetitions = repetitions;
  7593. return this;
  7594. },
  7595. // Weight
  7596. // set the weight stopping any scheduled fading
  7597. // although .enabled = false yields an effective weight of zero, this
  7598. // method does *not* change .enabled, because it would be confusing
  7599. setEffectiveWeight: function( weight ) {
  7600. this.weight = weight;
  7601. // note: same logic as when updated at runtime
  7602. this._effectiveWeight = this.enabled ? weight : 0;
  7603. return this.stopFading();
  7604. },
  7605. // return the weight considering fading and .enabled
  7606. getEffectiveWeight: function() {
  7607. return this._effectiveWeight;
  7608. },
  7609. fadeIn: function( duration ) {
  7610. return this._scheduleFading( duration, 0, 1 );
  7611. },
  7612. fadeOut: function( duration ) {
  7613. return this._scheduleFading( duration, 1, 0 );
  7614. },
  7615. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7616. var mixer = this._mixer;
  7617. fadeOutAction.fadeOut( duration );
  7618. this.fadeIn( duration );
  7619. if( warp ) {
  7620. var fadeInDuration = this._clip.duration,
  7621. fadeOutDuration = fadeOutAction._clip.duration,
  7622. startEndRatio = fadeOutDuration / fadeInDuration,
  7623. endStartRatio = fadeInDuration / fadeOutDuration;
  7624. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7625. this.warp( endStartRatio, 1.0, duration );
  7626. }
  7627. return this;
  7628. },
  7629. crossFadeTo: function( fadeInAction, duration, warp ) {
  7630. return fadeInAction.crossFadeFrom( this, duration, warp );
  7631. },
  7632. stopFading: function() {
  7633. var weightInterpolant = this._weightInterpolant;
  7634. if ( weightInterpolant !== null ) {
  7635. this._weightInterpolant = null;
  7636. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7637. }
  7638. return this;
  7639. },
  7640. // Time Scale Control
  7641. // set the weight stopping any scheduled warping
  7642. // although .paused = true yields an effective time scale of zero, this
  7643. // method does *not* change .paused, because it would be confusing
  7644. setEffectiveTimeScale: function( timeScale ) {
  7645. this.timeScale = timeScale;
  7646. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7647. return this.stopWarping();
  7648. },
  7649. // return the time scale considering warping and .paused
  7650. getEffectiveTimeScale: function() {
  7651. return this._effectiveTimeScale;
  7652. },
  7653. setDuration: function( duration ) {
  7654. this.timeScale = this._clip.duration / duration;
  7655. return this.stopWarping();
  7656. },
  7657. syncWith: function( action ) {
  7658. this.time = action.time;
  7659. this.timeScale = action.timeScale;
  7660. return this.stopWarping();
  7661. },
  7662. halt: function( duration ) {
  7663. return this.warp( this._currentTimeScale, 0, duration );
  7664. },
  7665. warp: function( startTimeScale, endTimeScale, duration ) {
  7666. var mixer = this._mixer, now = mixer.time,
  7667. interpolant = this._timeScaleInterpolant,
  7668. timeScale = this.timeScale;
  7669. if ( interpolant === null ) {
  7670. interpolant = mixer._lendControlInterpolant(),
  7671. this._timeScaleInterpolant = interpolant;
  7672. }
  7673. var times = interpolant.parameterPositions,
  7674. values = interpolant.sampleValues;
  7675. times[ 0 ] = now;
  7676. times[ 1 ] = now + duration;
  7677. values[ 0 ] = startTimeScale / timeScale;
  7678. values[ 1 ] = endTimeScale / timeScale;
  7679. return this;
  7680. },
  7681. stopWarping: function() {
  7682. var timeScaleInterpolant = this._timeScaleInterpolant;
  7683. if ( timeScaleInterpolant !== null ) {
  7684. this._timeScaleInterpolant = null;
  7685. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7686. }
  7687. return this;
  7688. },
  7689. // Object Accessors
  7690. getMixer: function() {
  7691. return this._mixer;
  7692. },
  7693. getClip: function() {
  7694. return this._clip;
  7695. },
  7696. getRoot: function() {
  7697. return this._localRoot || this._mixer._root;
  7698. },
  7699. // Interna
  7700. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7701. // called by the mixer
  7702. var startTime = this._startTime;
  7703. if ( startTime !== null ) {
  7704. // check for scheduled start of action
  7705. var timeRunning = ( time - startTime ) * timeDirection;
  7706. if ( timeRunning < 0 || timeDirection === 0 ) {
  7707. return; // yet to come / don't decide when delta = 0
  7708. }
  7709. // start
  7710. this._startTime = null; // unschedule
  7711. deltaTime = timeDirection * timeRunning;
  7712. }
  7713. // apply time scale and advance time
  7714. deltaTime *= this._updateTimeScale( time );
  7715. var clipTime = this._updateTime( deltaTime );
  7716. // note: _updateTime may disable the action resulting in
  7717. // an effective weight of 0
  7718. var weight = this._updateWeight( time );
  7719. if ( weight > 0 ) {
  7720. var interpolants = this._interpolants;
  7721. var propertyMixers = this._propertyBindings;
  7722. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7723. interpolants[ j ].evaluate( clipTime );
  7724. propertyMixers[ j ].accumulate( accuIndex, weight );
  7725. }
  7726. }
  7727. },
  7728. _updateWeight: function( time ) {
  7729. var weight = 0;
  7730. if ( this.enabled ) {
  7731. weight = this.weight;
  7732. var interpolant = this._weightInterpolant;
  7733. if ( interpolant !== null ) {
  7734. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7735. weight *= interpolantValue;
  7736. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7737. this.stopFading();
  7738. if ( interpolantValue === 0 ) {
  7739. // faded out, disable
  7740. this.enabled = false;
  7741. }
  7742. }
  7743. }
  7744. }
  7745. this._effectiveWeight = weight;
  7746. return weight;
  7747. },
  7748. _updateTimeScale: function( time ) {
  7749. var timeScale = 0;
  7750. if ( ! this.paused ) {
  7751. timeScale = this.timeScale;
  7752. var interpolant = this._timeScaleInterpolant;
  7753. if ( interpolant !== null ) {
  7754. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7755. timeScale *= interpolantValue;
  7756. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7757. this.stopWarping();
  7758. if ( timeScale === 0 ) {
  7759. // motion has halted, pause
  7760. this.pause = true;
  7761. } else {
  7762. // warp done - apply final time scale
  7763. this.timeScale = timeScale;
  7764. }
  7765. }
  7766. }
  7767. }
  7768. this._effectiveTimeScale = timeScale;
  7769. return timeScale;
  7770. },
  7771. _updateTime: function( deltaTime ) {
  7772. var time = this.time + deltaTime;
  7773. if ( deltaTime === 0 ) return time;
  7774. var duration = this._clip.duration,
  7775. loop = this.loop,
  7776. loopCount = this._loopCount,
  7777. pingPong = false;
  7778. switch ( loop ) {
  7779. case THREE.LoopOnce:
  7780. case THREE.LoopOnceClamp:
  7781. if ( loopCount === -1 ) {
  7782. // just started
  7783. this.loopCount = 0;
  7784. this._setEndings( true, true, false );
  7785. }
  7786. if ( time >= duration ) {
  7787. time = duration;
  7788. } else if ( time < 0 ) {
  7789. time = 0;
  7790. } else break;
  7791. // reached the end
  7792. if ( this.clampWhenFinished ) this.pause = true;
  7793. else this.enabled = false;
  7794. this._mixer.dispatchEvent( {
  7795. type: 'finished', action: this,
  7796. direction: deltaTime < 0 ? -1 : 1
  7797. } );
  7798. break;
  7799. case THREE.LoopPingPong:
  7800. pingPong = true;
  7801. case THREE.LoopRepeat:
  7802. if ( loopCount === -1 ) {
  7803. // just started
  7804. if ( deltaTime > 0 ) {
  7805. loopCount = 0;
  7806. this._setEndings(
  7807. true, this.repetitions === 0, pingPong );
  7808. } else {
  7809. // when looping in reverse direction, the initial
  7810. // transition through zero counts as a repetition,
  7811. // so leave loopCount at -1
  7812. this._setEndings(
  7813. this.repetitions === 0, true, pingPong );
  7814. }
  7815. }
  7816. if ( time >= duration || time < 0 ) {
  7817. // wrap around
  7818. var loopDelta = Math.floor( time / duration ); // signed
  7819. time -= duration * loopDelta;
  7820. loopCount += Math.abs( loopDelta );
  7821. var pending = this.repetitions - loopCount;
  7822. if ( pending < 0 ) {
  7823. // stop (switch state, clamp time, fire event)
  7824. if ( this.clampWhenFinished ) this.paused = true;
  7825. else this.enabled = false;
  7826. time = deltaTime > 0 ? duration : 0;
  7827. this._mixer.dispatchEvent( {
  7828. type: 'finished', action: this,
  7829. direction: deltaTime > 0 ? 1 : -1
  7830. } );
  7831. break;
  7832. } else if ( pending === 0 ) {
  7833. // transition to last round
  7834. var atStart = deltaTime < 0;
  7835. this._setEndings( atStart, ! atStart, pingPong );
  7836. } else {
  7837. this._setEndings( false, false, pingPong );
  7838. }
  7839. this._loopCount = loopCount;
  7840. this._mixer.dispatchEvent( {
  7841. type: 'loop', action: this, loopDelta: loopDelta
  7842. } );
  7843. }
  7844. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7845. // invert time for the "pong round"
  7846. this.time = time;
  7847. return duration - time;
  7848. }
  7849. break;
  7850. }
  7851. this.time = time;
  7852. return time;
  7853. },
  7854. _setEndings: function( atStart, atEnd, pingPong ) {
  7855. var settings = this._interpolantSettings;
  7856. if ( pingPong ) {
  7857. settings.endingStart = THREE.ZeroSlopeEnding;
  7858. settings.endingEnd = THREE.ZeroSlopeEnding;
  7859. } else {
  7860. // assuming for LoopOnce atStart == atEnd == true
  7861. if ( atStart ) {
  7862. settings.endingStart = this.zeroSlopeAtStart ?
  7863. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7864. } else {
  7865. settings.endingStart = THREE.WrapAroundEnding;
  7866. }
  7867. if ( atEnd ) {
  7868. settings.endingEnd = this.zeroSlopeAtEnd ?
  7869. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7870. } else {
  7871. settings.endingEnd = THREE.WrapAroundEnding;
  7872. }
  7873. }
  7874. },
  7875. _scheduleFading: function( duration, weightNow, weightThen ) {
  7876. var mixer = this._mixer, now = mixer.time,
  7877. interpolant = this._weightInterpolant;
  7878. if ( interpolant === null ) {
  7879. interpolant = mixer._lendControlInterpolant(),
  7880. this._weightInterpolant = interpolant;
  7881. }
  7882. var times = interpolant.parameterPositions,
  7883. values = interpolant.sampleValues;
  7884. times[ 0 ] = now; values[ 0 ] = weightNow;
  7885. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  7886. return this;
  7887. }
  7888. };
  7889. // Implementation details:
  7890. Object.assign( THREE.AnimationMixer.prototype, {
  7891. _bindAction: function( action, prototypeAction ) {
  7892. var root = action._localRoot || this._root,
  7893. tracks = action._clip.tracks,
  7894. nTracks = tracks.length,
  7895. bindings = action._propertyBindings,
  7896. interpolants = action._interpolants,
  7897. rootUuid = root.uuid,
  7898. bindingsByRoot = this._bindingsByRootAndName,
  7899. bindingsByName = bindingsByRoot[ rootUuid ];
  7900. if ( bindingsByName === undefined ) {
  7901. bindingsByName = {};
  7902. bindingsByRoot[ rootUuid ] = bindingsByName;
  7903. }
  7904. for ( var i = 0; i !== nTracks; ++ i ) {
  7905. var track = tracks[ i ],
  7906. trackName = track.name,
  7907. binding = bindingsByName[ trackName ];
  7908. if ( binding !== undefined ) {
  7909. bindings[ i ] = binding;
  7910. } else {
  7911. binding = bindings[ i ];
  7912. if ( binding !== undefined ) {
  7913. // existing binding, make sure the cache knows
  7914. if ( binding._cacheIndex === null ) {
  7915. ++ binding.referenceCount;
  7916. this._addInactiveBinding( binding, rootUuid, trackName );
  7917. }
  7918. continue;
  7919. }
  7920. var path = prototypeAction && prototypeAction.
  7921. _propertyBindings[ i ].binding.parsedPath;
  7922. binding = new THREE.PropertyMixer(
  7923. THREE.PropertyBinding.create( root, trackName, path ),
  7924. track.ValueTypeName, track.getValueSize() );
  7925. ++ binding.referenceCount;
  7926. this._addInactiveBinding( binding, rootUuid, trackName );
  7927. bindings[ i ] = binding;
  7928. }
  7929. interpolants[ i ].resultBuffer = binding.buffer;
  7930. }
  7931. },
  7932. _activateAction: function( action ) {
  7933. if ( ! this._isActiveAction( action ) ) {
  7934. if ( action._cacheIndex === null ) {
  7935. // this action has been forgotten by the cache, but the user
  7936. // appears to be still using it -> rebind
  7937. var rootUuid = ( action._localRoot || this._root ).uuid,
  7938. clipName = action._clip.name,
  7939. actionsForClip = this._actionsByClip[ clipName ];
  7940. this._bindAction( action,
  7941. actionsForClip && actionsForClip.knownActions[ 0 ] );
  7942. this._addInactiveAction( action, clipName, rootUuid );
  7943. }
  7944. var bindings = action._propertyBindings;
  7945. // increment reference counts / sort out state
  7946. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7947. var binding = bindings[ i ];
  7948. if ( binding.useCount ++ === 0 ) {
  7949. this._lendBinding( binding );
  7950. binding.saveOriginalState();
  7951. }
  7952. }
  7953. this._lendAction( action );
  7954. }
  7955. },
  7956. _deactivateAction: function( action ) {
  7957. if ( this._isActiveAction( action ) ) {
  7958. var bindings = action._propertyBindings;
  7959. // decrement reference counts / sort out state
  7960. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7961. var binding = bindings[ i ];
  7962. if ( -- binding.useCount === 0 ) {
  7963. binding.restoreOriginalState();
  7964. this._takeBackBinding( binding );
  7965. }
  7966. }
  7967. this._takeBackAction( action );
  7968. }
  7969. },
  7970. // Memory manager
  7971. _initMemoryManager: function() {
  7972. this._actions = []; // 'nActiveActions' followed by inactive ones
  7973. this._nActiveActions = 0;
  7974. this._actionsByClip = {};
  7975. // inside:
  7976. // {
  7977. // knownActions: Array< _Action > - used as prototypes
  7978. // actionByRoot: _Action - lookup
  7979. // }
  7980. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  7981. this._nActiveBindings = 0;
  7982. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  7983. this._controlInterpolants = []; // same game as above
  7984. this._nActiveControlInterpolants = 0;
  7985. var scope = this;
  7986. this.stats = {
  7987. actions: {
  7988. get total() { return scope._actions.length; },
  7989. get inUse() { return scope._nActiveActions; }
  7990. },
  7991. bindings: {
  7992. get total() { return scope._bindings.length; },
  7993. get inUse() { return scope._nActiveBindings; }
  7994. },
  7995. controlInterpolants: {
  7996. get total() { return scope._controlInterpolants.length; },
  7997. get inUse() { return scope._nActiveControlInterpolants; }
  7998. }
  7999. };
  8000. },
  8001. // Memory management for _Action objects
  8002. _isActiveAction: function( action ) {
  8003. var index = action._cacheIndex;
  8004. return index !== null && index < this._nActiveActions;
  8005. },
  8006. _addInactiveAction: function( action, clipName, rootUuid ) {
  8007. var actions = this._actions,
  8008. actionsByClip = this._actionsByClip,
  8009. actionsForClip = actionsByClip[ clipName ];
  8010. if ( actionsForClip === undefined ) {
  8011. actionsForClip = {
  8012. knownActions: [ action ],
  8013. actionByRoot: {}
  8014. };
  8015. action._byClipCacheIndex = 0;
  8016. actionsByClip[ clipName ] = actionsForClip;
  8017. } else {
  8018. var knownActions = actionsForClip.knownActions;
  8019. action._byClipCacheIndex = knownActions.length;
  8020. knownActions.push( action );
  8021. }
  8022. action._cacheIndex = actions.length;
  8023. actions.push( action );
  8024. actionsForClip.actionByRoot[ rootUuid ] = action;
  8025. },
  8026. _removeInactiveAction: function( action ) {
  8027. var actions = this._actions,
  8028. lastInactiveAction = actions[ actions.length - 1 ],
  8029. cacheIndex = action._cacheIndex;
  8030. lastInactiveAction._cacheIndex = cacheIndex;
  8031. actions[ cacheIndex ] = lastInactiveAction;
  8032. actions.pop();
  8033. action._cacheIndex = null;
  8034. var clipName = action._clip.name,
  8035. actionsByClip = this._actionsByClip,
  8036. actionsForClip = actionsByClip[ clipName ],
  8037. knownActionsForClip = actionsForClip.knownActions,
  8038. lastKnownAction =
  8039. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8040. byClipCacheIndex = action._byClipCacheIndex;
  8041. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8042. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8043. knownActionsForClip.pop();
  8044. action._byClipCacheIndex = null;
  8045. var actionByRoot = actionsForClip.actionByRoot,
  8046. rootUuid = ( actions._localRoot || this._root ).uuid;
  8047. delete actionByRoot[ rootUuid ];
  8048. if ( knownActionsForClip.length === 0 ) {
  8049. delete actionsByClip[ clipName ];
  8050. }
  8051. this._removeInactiveBindingsForAction( action );
  8052. },
  8053. _removeInactiveBindingsForAction: function( action ) {
  8054. var bindings = action._propertyBindings;
  8055. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8056. var binding = bindings[ i ];
  8057. if ( -- binding.referenceCount === 0 ) {
  8058. this._removeInactiveBinding( binding );
  8059. }
  8060. }
  8061. },
  8062. _lendAction: function( action ) {
  8063. // [ active actions | inactive actions ]
  8064. // [ active actions >| inactive actions ]
  8065. // s a
  8066. // <-swap->
  8067. // a s
  8068. var actions = this._actions,
  8069. prevIndex = action._cacheIndex,
  8070. lastActiveIndex = this._nActiveActions ++,
  8071. firstInactiveAction = actions[ lastActiveIndex ];
  8072. action._cacheIndex = lastActiveIndex;
  8073. actions[ lastActiveIndex ] = action;
  8074. firstInactiveAction._cacheIndex = prevIndex;
  8075. actions[ prevIndex ] = firstInactiveAction;
  8076. },
  8077. _takeBackAction: function( action ) {
  8078. // [ active actions | inactive actions ]
  8079. // [ active actions |< inactive actions ]
  8080. // a s
  8081. // <-swap->
  8082. // s a
  8083. var actions = this._actions,
  8084. prevIndex = action._cacheIndex,
  8085. firstInactiveIndex = -- this._nActiveActions,
  8086. lastActiveAction = actions[ firstInactiveIndex ];
  8087. action._cacheIndex = firstInactiveIndex;
  8088. actions[ firstInactiveIndex ] = action;
  8089. lastActiveAction._cacheIndex = prevIndex;
  8090. actions[ prevIndex ] = lastActiveAction;
  8091. },
  8092. // Memory management for PropertyMixer objects
  8093. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8094. var bindingsByRoot = this._bindingsByRootAndName,
  8095. bindingByName = bindingsByRoot[ rootUuid ],
  8096. bindings = this._bindings;
  8097. if ( bindingByName === undefined ) {
  8098. bindingByName = {};
  8099. bindingsByRoot[ rootUuid ] = bindingByName;
  8100. }
  8101. bindingByName[ trackName ] = binding;
  8102. binding._cacheIndex = bindings.length;
  8103. bindings.push( binding );
  8104. },
  8105. _removeInactiveBinding: function( binding ) {
  8106. var bindings = this._bindings,
  8107. propBinding = binding.binding,
  8108. rootUuid = propBinding.rootNode.uuid,
  8109. trackName = propBinding.path,
  8110. bindingsByRoot = this._bindingsByRootAndName,
  8111. bindingByName = bindingsByRoot[ rootUuid ],
  8112. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8113. cacheIndex = binding._cacheIndex;
  8114. lastInactiveBinding._cacheIndex = cacheIndex;
  8115. bindings[ cacheIndex ] = lastInactiveBinding;
  8116. bindings.pop();
  8117. delete bindingByName[ trackName ];
  8118. remove_empty_map: {
  8119. for ( var _ in bindingByName ) break remove_empty_map;
  8120. delete bindingsByRoot[ rootUuid ];
  8121. }
  8122. },
  8123. _lendBinding: function( binding ) {
  8124. var bindings = this._bindings,
  8125. prevIndex = binding._cacheIndex,
  8126. lastActiveIndex = this._nActiveBindings ++,
  8127. firstInactiveBinding = bindings[ lastActiveIndex ];
  8128. binding._cacheIndex = lastActiveIndex;
  8129. bindings[ lastActiveIndex ] = binding;
  8130. firstInactiveBinding._cacheIndex = prevIndex;
  8131. bindings[ prevIndex ] = firstInactiveBinding;
  8132. },
  8133. _takeBackBinding: function( binding ) {
  8134. var bindings = this._bindings,
  8135. prevIndex = binding._cacheIndex,
  8136. firstInactiveIndex = -- this._nActiveBindings,
  8137. lastActiveBinding = bindings[ firstInactiveIndex ];
  8138. binding._cacheIndex = firstInactiveIndex;
  8139. bindings[ firstInactiveIndex ] = binding;
  8140. lastActiveBinding._cacheIndex = prevIndex;
  8141. bindings[ prevIndex ] = lastActiveBinding;
  8142. },
  8143. // Memory management of Interpolants for weight and time scale
  8144. _lendControlInterpolant: function() {
  8145. var interpolants = this._controlInterpolants,
  8146. lastActiveIndex = this._nActiveControlInterpolants ++,
  8147. interpolant = interpolants[ lastActiveIndex ];
  8148. if ( interpolant === undefined ) {
  8149. interpolant = new THREE.LinearInterpolant(
  8150. new Float32Array( 2 ), new Float32Array( 2 ),
  8151. 1, this._controlInterpolantsResultBuffer );
  8152. interpolant.__cacheIndex = lastActiveIndex;
  8153. interpolants[ lastActiveIndex ] = interpolant;
  8154. }
  8155. return interpolant;
  8156. },
  8157. _takeBackControlInterpolant: function( interpolant ) {
  8158. var interpolants = this._controlInterpolants,
  8159. prevIndex = interpolant.__cacheIndex,
  8160. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8161. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8162. interpolant.__cacheIndex = firstInactiveIndex;
  8163. interpolants[ firstInactiveIndex ] = interpolant;
  8164. lastActiveInterpolant.__cacheIndex = prevIndex;
  8165. interpolants[ prevIndex ] = lastActiveInterpolant;
  8166. },
  8167. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8168. } );
  8169. // File:src/animation/AnimationObjectGroup.js
  8170. /**
  8171. *
  8172. * A group of objects that receives a shared animation state.
  8173. *
  8174. * Usage:
  8175. *
  8176. * - Add objects you would otherwise pass as 'root' to the
  8177. * constructor or the .clipAction method of AnimationMixer.
  8178. *
  8179. * - Instead pass this object as 'root'.
  8180. *
  8181. * - You can also add and remove objects later when the mixer
  8182. * is running.
  8183. *
  8184. * Note:
  8185. *
  8186. * Objects of this class appear as one object to the mixer,
  8187. * so cache control of the individual objects must be done
  8188. * on the group.
  8189. *
  8190. * Limitation:
  8191. *
  8192. * - The animated properties must be compatible among the
  8193. * all objects in the group.
  8194. *
  8195. * - A single property can either be controlled through a
  8196. * target group or directly, but not both.
  8197. *
  8198. * @author tschw
  8199. */
  8200. THREE.AnimationObjectGroup = function( var_args ) {
  8201. this.uuid = THREE.Math.generateUUID();
  8202. // cached objects followed by the active ones
  8203. this._objects = Array.prototype.slice.call( arguments );
  8204. this.nCachedObjects_ = 0; // threshold
  8205. // note: read by PropertyBinding.Composite
  8206. var indices = {};
  8207. this._indicesByUUID = indices; // for bookkeeping
  8208. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8209. indices[ arguments[ i ].uuid ] = i;
  8210. }
  8211. this._paths = []; // inside: string
  8212. this._parsedPaths = []; // inside: { we don't care, here }
  8213. this._bindings = []; // inside: Array< PropertyBinding >
  8214. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8215. var scope = this;
  8216. this.stats = {
  8217. objects: {
  8218. get total() { return scope._objects.length; },
  8219. get inUse() { return this.total - scope.nCachedObjects_; }
  8220. },
  8221. get bindingsPerObject() { return scope._bindings.length; }
  8222. };
  8223. };
  8224. THREE.AnimationObjectGroup.prototype = {
  8225. constructor: THREE.AnimationObjectGroup,
  8226. add: function( var_args ) {
  8227. var objects = this._objects,
  8228. nObjects = objects.length,
  8229. nCachedObjects = this.nCachedObjects_,
  8230. indicesByUUID = this._indicesByUUID,
  8231. paths = this._paths,
  8232. parsedPaths = this._parsedPaths,
  8233. bindings = this._bindings,
  8234. nBindings = bindings.length;
  8235. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8236. var object = arguments[ i ],
  8237. uuid = object.uuid,
  8238. index = indicesByUUID[ uuid ];
  8239. if ( index === undefined ) {
  8240. // unknown object -> add it to the ACTIVE region
  8241. index = nObjects ++;
  8242. indicesByUUID[ uuid ] = index;
  8243. objects.push( object );
  8244. // accounting is done, now do the same for all bindings
  8245. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8246. bindings[ j ].push(
  8247. new THREE.PropertyBinding(
  8248. object, paths[ j ], parsedPaths[ j ] ) );
  8249. }
  8250. } else if ( index < nCachedObjects ) {
  8251. var knownObject = objects[ index ];
  8252. // move existing object to the ACTIVE region
  8253. var firstActiveIndex = -- nCachedObjects,
  8254. lastCachedObject = objects[ firstActiveIndex ];
  8255. indicesByUUID[ lastCachedObject.uuid ] = index;
  8256. objects[ index ] = lastCachedObject;
  8257. indicesByUUID[ uuid ] = firstActiveIndex;
  8258. objects[ firstActiveIndex ] = object;
  8259. // accounting is done, now do the same for all bindings
  8260. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8261. var bindingsForPath = bindings[ j ],
  8262. lastCached = bindingsForPath[ firstActiveIndex ],
  8263. binding = bindingsForPath[ index ];
  8264. bindingsForPath[ index ] = lastCached;
  8265. if ( binding === undefined ) {
  8266. // since we do not bother to create new bindings
  8267. // for objects that are cached, the binding may
  8268. // or may not exist
  8269. binding = new THREE.PropertyBinding(
  8270. object, paths[ j ], parsedPaths[ j ] );
  8271. }
  8272. bindingsForPath[ firstActiveIndex ] = binding;
  8273. }
  8274. } else if ( objects[ index ] !== knownObject) {
  8275. console.error( "Different objects with the same UUID " +
  8276. "detected. Clean the caches or recreate your " +
  8277. "infrastructure when reloading scenes..." );
  8278. } // else the object is already where we want it to be
  8279. } // for arguments
  8280. this.nCachedObjects_ = nCachedObjects;
  8281. },
  8282. remove: function( var_args ) {
  8283. var objects = this._objects,
  8284. nObjects = objects.length,
  8285. nCachedObjects = this.nCachedObjects_,
  8286. indicesByUUID = this._indicesByUUID,
  8287. bindings = this._bindings,
  8288. nBindings = bindings.length;
  8289. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8290. var object = arguments[ i ],
  8291. uuid = object.uuid,
  8292. index = indicesByUUID[ uuid ];
  8293. if ( index !== undefined && index >= nCachedObjects ) {
  8294. // move existing object into the CACHED region
  8295. var lastCachedIndex = nCachedObjects ++,
  8296. firstActiveObject = objects[ lastCachedIndex ];
  8297. indicesByUUID[ firstActiveObject.uuid ] = index;
  8298. objects[ index ] = firstActiveObject;
  8299. indicesByUUID[ uuid ] = lastCachedIndex;
  8300. objects[ lastCachedIndex ] = object;
  8301. // accounting is done, now do the same for all bindings
  8302. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8303. var bindingsForPath = bindings[ j ],
  8304. firstActive = bindingsForPath[ lastCachedIndex ],
  8305. binding = bindingsForPath[ index ];
  8306. bindingsForPath[ index ] = firstActive;
  8307. bindingsForPath[ lastCachedIndex ] = binding;
  8308. }
  8309. }
  8310. } // for arguments
  8311. this.nCachedObjects_ = nCachedObjects;
  8312. },
  8313. // remove & forget
  8314. uncache: function( var_args ) {
  8315. var objects = this._objects,
  8316. nObjects = objects.length,
  8317. nCachedObjects = this.nCachedObjects_,
  8318. indicesByUUID = this._indicesByUUID,
  8319. bindings = this._bindings,
  8320. nBindings = bindings.length;
  8321. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8322. var object = arguments[ i ],
  8323. uuid = object.uuid,
  8324. index = indicesByUUID[ uuid ];
  8325. if ( index !== undefined ) {
  8326. delete indicesByUUID[ uuid ];
  8327. if ( index < nCachedObjects ) {
  8328. // object is cached, shrink the CACHED region
  8329. var firstActiveIndex = -- nCachedObjects,
  8330. lastCachedObject = objects[ firstActiveIndex ],
  8331. lastIndex = -- nObjects,
  8332. lastObject = objects[ lastIndex ];
  8333. // last cached object takes this object's place
  8334. indicesByUUID[ lastCachedObject.uuid ] = index;
  8335. objects[ index ] = lastCachedObject;
  8336. // last object goes to the activated slot and pop
  8337. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8338. objects[ firstActiveIndex ] = lastObject;
  8339. objects.pop();
  8340. // accounting is done, now do the same for all bindings
  8341. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8342. var bindingsForPath = bindings[ j ],
  8343. lastCached = bindingsForPath[ firstActiveIndex ],
  8344. last = bindingsForPath[ lastIndex ];
  8345. bindingsForPath[ index ] = lastCached;
  8346. bindingsForPath[ firstActiveIndex ] = last;
  8347. bindingsForPath.pop();
  8348. }
  8349. } else {
  8350. // object is active, just swap with the last and pop
  8351. var lastIndex = -- nObjects,
  8352. lastObject = objects[ lastIndex ];
  8353. indicesByUUID[ lastObject.uuid ] = index;
  8354. objects[ index ] = lastObject;
  8355. objects.pop();
  8356. // accounting is done, now do the same for all bindings
  8357. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8358. var bindingsForPath = bindings[ j ];
  8359. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8360. bindingsForPath.pop();
  8361. }
  8362. } // cached or active
  8363. } // if object is known
  8364. } // for arguments
  8365. this.nCachedObjects_ = nCachedObjects;
  8366. },
  8367. // Internal interface used by befriended PropertyBinding.Composite:
  8368. subscribe_: function( path, parsedPath ) {
  8369. // returns an array of bindings for the given path that is changed
  8370. // according to the contained objects in the group
  8371. var indicesByPath = this._bindingsIndicesByPath,
  8372. index = indicesByPath[ path ],
  8373. bindings = this._bindings;
  8374. if ( index !== undefined ) return bindings[ index ];
  8375. var paths = this._paths,
  8376. parsedPaths = this._parsedPaths,
  8377. objects = this._objects,
  8378. nObjects = objects.length,
  8379. nCachedObjects = this.nCachedObjects_,
  8380. bindingsForPath = new Array( nObjects );
  8381. index = bindings.length;
  8382. indicesByPath[ path ] = index;
  8383. paths.push( path );
  8384. parsedPaths.push( parsedPath );
  8385. bindings.push( bindingsForPath );
  8386. for ( var i = nCachedObjects,
  8387. n = objects.length; i !== n; ++ i ) {
  8388. var object = objects[ i ];
  8389. bindingsForPath[ i ] =
  8390. new THREE.PropertyBinding( object, path, parsedPath );
  8391. }
  8392. return bindingsForPath;
  8393. },
  8394. unsubscribe_: function( path ) {
  8395. // tells the group to forget about a property path and no longer
  8396. // update the array previously obtained with 'subscribe_'
  8397. var indicesByPath = this._bindingsIndicesByPath,
  8398. index = indicesByPath[ path ];
  8399. if ( index !== undefined ) {
  8400. var paths = this._paths,
  8401. parsedPaths = this._parsedPaths,
  8402. bindings = this._bindings,
  8403. lastBindingsIndex = bindings.length - 1,
  8404. lastBindings = bindings[ lastBindingsIndex ],
  8405. lastBindingsPath = path[ lastBindingsIndex ];
  8406. indicesByPath[ lastBindingsPath ] = index;
  8407. bindings[ index ] = lastBindings;
  8408. bindings.pop();
  8409. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8410. parsedPaths.pop();
  8411. paths[ index ] = paths[ lastBindingsIndex ];
  8412. paths.pop();
  8413. }
  8414. }
  8415. };
  8416. // File:src/animation/AnimationUtils.js
  8417. /**
  8418. * @author tschw
  8419. * @author Ben Houston / http://clara.io/
  8420. * @author David Sarno / http://lighthaus.us/
  8421. */
  8422. THREE.AnimationUtils = {
  8423. // same as Array.prototype.slice, but also works on typed arrays
  8424. arraySlice: function( array, from, to ) {
  8425. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8426. return new array.constructor( array.subarray( from, to ) );
  8427. }
  8428. return array.slice( from, to );
  8429. },
  8430. // converts an array to a specific type
  8431. convertArray: function( array, type, forceClone ) {
  8432. if ( ! array || // let 'undefined' and 'null' pass
  8433. ! forceClone && array.constructor === type ) return array;
  8434. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8435. return new type( array ); // create typed array
  8436. }
  8437. return Array.prototype.slice.call( array ); // create Array
  8438. },
  8439. isTypedArray: function( object ) {
  8440. return ArrayBuffer.isView( object ) &&
  8441. ! ( object instanceof DataView );
  8442. },
  8443. // returns an array by which times and values can be sorted
  8444. getKeyframeOrder: function( times ) {
  8445. function compareTime( i, j ) {
  8446. return times[ i ] - times[ j ];
  8447. }
  8448. var n = times.length;
  8449. var result = new Array( n );
  8450. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8451. result.sort( compareTime );
  8452. return result;
  8453. },
  8454. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8455. sortedArray: function( values, stride, order ) {
  8456. var nValues = values.length;
  8457. var result = new values.constructor( nValues );
  8458. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8459. var srcOffset = order[ i ] * stride;
  8460. for ( var j = 0; j !== stride; ++ j ) {
  8461. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8462. }
  8463. }
  8464. return result;
  8465. },
  8466. // function for parsing AOS keyframe formats
  8467. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8468. var i = 1, key = jsonKeys[ 0 ];
  8469. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8470. key = jsonKeys[ i ++ ];
  8471. }
  8472. if ( key === undefined ) return; // no data
  8473. var value = key[ valuePropertyName ];
  8474. if ( value === undefined ) return; // no data
  8475. if ( Array.isArray( value ) ) {
  8476. do {
  8477. value = key[ valuePropertyName ];
  8478. if ( value !== undefined ) {
  8479. times.push( key.time );
  8480. values.push.apply( values, value ); // push all elements
  8481. }
  8482. key = jsonKeys[ i ++ ];
  8483. } while ( key !== undefined );
  8484. } else if ( value.toArray !== undefined ) {
  8485. // ...assume THREE.Math-ish
  8486. do {
  8487. value = key[ valuePropertyName ];
  8488. if ( value !== undefined ) {
  8489. times.push( key.time );
  8490. value.toArray( values, values.length );
  8491. }
  8492. key = jsonKeys[ i ++ ];
  8493. } while ( key !== undefined );
  8494. } else {
  8495. // otherwise push as-is
  8496. do {
  8497. value = key[ valuePropertyName ];
  8498. if ( value !== undefined ) {
  8499. times.push( key.time );
  8500. values.push( value );
  8501. }
  8502. key = jsonKeys[ i ++ ];
  8503. } while ( key !== undefined );
  8504. }
  8505. }
  8506. };
  8507. // File:src/animation/KeyframeTrack.js
  8508. /**
  8509. *
  8510. * A timed sequence of keyframes for a specific property.
  8511. *
  8512. *
  8513. * @author Ben Houston / http://clara.io/
  8514. * @author David Sarno / http://lighthaus.us/
  8515. * @author tschw
  8516. */
  8517. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8518. if( name === undefined ) throw new Error( "track name is undefined" );
  8519. if( times === undefined || times.length === 0 ) {
  8520. throw new Error( "no keyframes in track named " + name );
  8521. }
  8522. this.name = name;
  8523. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8524. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8525. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8526. this.validate();
  8527. this.optimize();
  8528. };
  8529. THREE.KeyframeTrack.prototype = {
  8530. constructor: THREE.KeyframeTrack,
  8531. TimeBufferType: Float32Array,
  8532. ValueBufferType: Float32Array,
  8533. DefaultInterpolation: THREE.InterpolateLinear,
  8534. InterpolantFactoryMethodDiscrete: function( result ) {
  8535. return new THREE.DiscreteInterpolant(
  8536. this.times, this.values, this.getValueSize(), result );
  8537. },
  8538. InterpolantFactoryMethodLinear: function( result ) {
  8539. return new THREE.LinearInterpolant(
  8540. this.times, this.values, this.getValueSize(), result );
  8541. },
  8542. InterpolantFactoryMethodSmooth: function( result ) {
  8543. return new THREE.CubicInterpolant(
  8544. this.times, this.values, this.getValueSize(), result );
  8545. },
  8546. setInterpolation: function( interpolation ) {
  8547. var factoryMethod = undefined;
  8548. switch ( interpolation ) {
  8549. case THREE.InterpolateDiscrete:
  8550. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8551. break;
  8552. case THREE.InterpolateLinear:
  8553. factoryMethod = this.InterpolantFactoryMethodLinear;
  8554. break;
  8555. case THREE.InterpolateSmooth:
  8556. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8557. break;
  8558. }
  8559. if ( factoryMethod === undefined ) {
  8560. var message = "unsupported interpolation for " +
  8561. this.ValueTypeName + " keyframe track named " + this.name;
  8562. if ( this.createInterpolant === undefined ) {
  8563. // fall back to default, unless the default itself is messed up
  8564. if ( interpolation !== this.DefaultInterpolation ) {
  8565. this.setInterpolation( this.DefaultInterpolation );
  8566. } else {
  8567. throw new Error( message ); // fatal, in this case
  8568. }
  8569. }
  8570. console.warn( message );
  8571. return;
  8572. }
  8573. this.createInterpolant = factoryMethod;
  8574. },
  8575. getInterpolation: function() {
  8576. switch ( this.createInterpolant ) {
  8577. case this.InterpolantFactoryMethodDiscrete:
  8578. return THREE.InterpolateDiscrete;
  8579. case this.InterpolantFactoryMethodLinear:
  8580. return THREE.InterpolateLinear;
  8581. case this.InterpolantFactoryMethodSmooth:
  8582. return THREE.InterpolateSmooth;
  8583. }
  8584. },
  8585. getValueSize: function() {
  8586. return this.values.length / this.times.length;
  8587. },
  8588. // move all keyframes either forwards or backwards in time
  8589. shift: function( timeOffset ) {
  8590. if( timeOffset !== 0.0 ) {
  8591. var times = this.times;
  8592. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8593. times[ i ] += timeOffset;
  8594. }
  8595. }
  8596. return this;
  8597. },
  8598. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8599. scale: function( timeScale ) {
  8600. if( timeScale !== 1.0 ) {
  8601. var times = this.times;
  8602. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8603. times[ i ] *= timeScale;
  8604. }
  8605. }
  8606. return this;
  8607. },
  8608. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8609. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8610. trim: function( startTime, endTime ) {
  8611. var times = this.times;
  8612. var nKeys = times.length;
  8613. var firstKeysToRemove = 0;
  8614. for ( var i = 1; i !== nKeys; ++ i ) {
  8615. if ( times[i] <= startTime ) ++ firstKeysToRemove;
  8616. }
  8617. var lastKeysToRemove = 0;
  8618. for ( var i = nKeys - 2; i !== 0; -- i ) {
  8619. if ( times[i] >= endTime ) ++ lastKeysToRemove;
  8620. else break;
  8621. }
  8622. // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily)
  8623. if( ( firstKeysToRemove + lastKeysToRemove ) !== 0 ) {
  8624. var from = firstKeysToRemove;
  8625. var to = nKeys - lastKeysToRemove - firstKeysToRemove;
  8626. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8627. var values = this.values;
  8628. var stride = this.getValueSize();
  8629. this.values = THREE.AnimationUtils.arraySlice( values, from * stride, to * stride );
  8630. }
  8631. return this;
  8632. },
  8633. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8634. validate: function() {
  8635. var valid = true;
  8636. var valueSize = this.getValueSize();
  8637. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8638. console.error( "invalid value size in track", this );
  8639. valid = false;
  8640. }
  8641. var times = this.times,
  8642. values = this.values,
  8643. nKeys = times.length;
  8644. if( nKeys === 0 ) {
  8645. console.error( "track is empty", this );
  8646. valid = false;
  8647. }
  8648. var prevTime = null;
  8649. for( var i = 0; i !== nKeys; i ++ ) {
  8650. var currTime = times[ i ];
  8651. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8652. console.error( "time is not a valid number", this, i, currTime );
  8653. valid = false;
  8654. break;
  8655. }
  8656. if( prevTime !== null && prevTime > currTime ) {
  8657. console.error( "out of order keys", this, i, currTime, prevTime );
  8658. valid = false;
  8659. break;
  8660. }
  8661. prevTime = currTime;
  8662. }
  8663. if ( values !== undefined ) {
  8664. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8665. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8666. var value = values[ i ];
  8667. if ( isNaN( value ) ) {
  8668. console.error( "value is not a valid number", this, i, value );
  8669. valid = false;
  8670. break;
  8671. }
  8672. }
  8673. }
  8674. }
  8675. return valid;
  8676. },
  8677. // removes equivalent sequential keys as common in morph target sequences
  8678. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8679. optimize: function() {
  8680. var times = this.times,
  8681. values = this.values,
  8682. stride = this.getValueSize(),
  8683. writeIndex = 1;
  8684. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8685. var keep = false;
  8686. var time = times[ i ];
  8687. var timeNext = times[ i + 1 ];
  8688. // remove adjacent keyframes scheduled at the same time
  8689. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8690. // remove unnecessary keyframes same as their neighbors
  8691. var offset = i * stride,
  8692. offsetP = offset - stride,
  8693. offsetN = offset + stride;
  8694. for ( var j = 0; j !== stride; ++ j ) {
  8695. var value = values[ offset + j ];
  8696. if ( value !== values[ offsetP + j ] ||
  8697. value !== values[ offsetN + j ] ) {
  8698. keep = true;
  8699. break;
  8700. }
  8701. }
  8702. }
  8703. // in-place compaction
  8704. if ( keep ) {
  8705. if ( i !== writeIndex ) {
  8706. times[ writeIndex ] = times[ i ];
  8707. var readOffset = i * stride,
  8708. writeOffset = writeIndex * stride;
  8709. for ( var j = 0; j !== stride; ++ j ) {
  8710. values[ writeOffset + j ] = values[ readOffset + j ];
  8711. }
  8712. }
  8713. ++ writeIndex;
  8714. }
  8715. }
  8716. if ( writeIndex !== times.length ) {
  8717. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8718. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8719. }
  8720. return this;
  8721. }
  8722. };
  8723. // Static methods:
  8724. Object.assign( THREE.KeyframeTrack, {
  8725. // Serialization (in static context, because of constructor invocation
  8726. // and automatic invocation of .toJSON):
  8727. parse: function( json ) {
  8728. if( json.type === undefined ) {
  8729. throw new Error( "track type undefined, can not parse" );
  8730. }
  8731. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8732. if ( json.times === undefined ) {
  8733. console.warn( "legacy JSON format detected, converting" );
  8734. var times = [], values = [];
  8735. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8736. json.times = times;
  8737. json.values = values;
  8738. }
  8739. // derived classes can define a static parse method
  8740. if ( trackType.parse !== undefined ) {
  8741. return trackType.parse( json );
  8742. } else {
  8743. // by default, we asssume a constructor compatible with the base
  8744. return new trackType(
  8745. json.name, json.times, json.values, json.interpolation );
  8746. }
  8747. },
  8748. toJSON: function( track ) {
  8749. var trackType = track.constructor;
  8750. var json;
  8751. // derived classes can define a static toJSON method
  8752. if ( trackType.toJSON !== undefined ) {
  8753. json = trackType.toJSON( track );
  8754. } else {
  8755. // by default, we assume the data can be serialized as-is
  8756. json = {
  8757. 'name': track.name,
  8758. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8759. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8760. };
  8761. var interpolation = track.getInterpolation();
  8762. if ( interpolation !== track.DefaultInterpolation ) {
  8763. json.interpolation = interpolation;
  8764. }
  8765. }
  8766. json.type = track.ValueTypeName; // mandatory
  8767. return json;
  8768. },
  8769. _getTrackTypeForValueTypeName: function( typeName ) {
  8770. switch( typeName.toLowerCase() ) {
  8771. case "scalar":
  8772. case "double":
  8773. case "float":
  8774. case "number":
  8775. case "integer":
  8776. return THREE.NumberKeyframeTrack;
  8777. case "vector":
  8778. case "vector2":
  8779. case "vector3":
  8780. case "vector4":
  8781. return THREE.VectorKeyframeTrack;
  8782. case "color":
  8783. return THREE.ColorKeyframeTrack;
  8784. case "quaternion":
  8785. return THREE.QuaternionKeyframeTrack;
  8786. case "bool":
  8787. case "boolean":
  8788. return THREE.BooleanKeyframeTrack;
  8789. case "string":
  8790. return THREE.StringKeyframeTrack;
  8791. };
  8792. throw new Error( "Unsupported typeName: " + typeName );
  8793. }
  8794. } );
  8795. // File:src/animation/PropertyBinding.js
  8796. /**
  8797. *
  8798. * A reference to a real property in the scene graph.
  8799. *
  8800. *
  8801. * @author Ben Houston / http://clara.io/
  8802. * @author David Sarno / http://lighthaus.us/
  8803. * @author tschw
  8804. */
  8805. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8806. this.path = path;
  8807. this.parsedPath = parsedPath ||
  8808. THREE.PropertyBinding.parseTrackName( path );
  8809. this.node = THREE.PropertyBinding.findNode(
  8810. rootNode, this.parsedPath.nodeName ) || rootNode;
  8811. this.rootNode = rootNode;
  8812. };
  8813. THREE.PropertyBinding.prototype = {
  8814. constructor: THREE.PropertyBinding,
  8815. getValue: function getValue_unbound( targetArray, offset ) {
  8816. this.bind();
  8817. this.getValue( targetArray, offset );
  8818. // Note: This class uses a State pattern on a per-method basis:
  8819. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8820. // prototype version of these methods with one that represents
  8821. // the bound state. When the property is not found, the methods
  8822. // become no-ops.
  8823. },
  8824. setValue: function getValue_unbound( sourceArray, offset ) {
  8825. this.bind();
  8826. this.setValue( sourceArray, offset );
  8827. },
  8828. // create getter / setter pair for a property in the scene graph
  8829. bind: function() {
  8830. var targetObject = this.node,
  8831. parsedPath = this.parsedPath,
  8832. objectName = parsedPath.objectName,
  8833. propertyName = parsedPath.propertyName,
  8834. propertyIndex = parsedPath.propertyIndex;
  8835. if ( ! targetObject ) {
  8836. targetObject = THREE.PropertyBinding.findNode(
  8837. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8838. this.node = targetObject;
  8839. }
  8840. // set fail state so we can just 'return' on error
  8841. this.getValue = this._getValue_unavailable;
  8842. this.setValue = this._setValue_unavailable;
  8843. // ensure there is a value node
  8844. if ( ! targetObject ) {
  8845. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8846. return;
  8847. }
  8848. if( objectName ) {
  8849. var objectIndex = parsedPath.objectIndex;
  8850. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8851. switch ( objectName ) {
  8852. case 'materials':
  8853. if( ! targetObject.material ) {
  8854. console.error( ' can not bind to material as node does not have a material', this );
  8855. return;
  8856. }
  8857. if( ! targetObject.material.materials ) {
  8858. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8859. return;
  8860. }
  8861. targetObject = targetObject.material.materials;
  8862. break;
  8863. case 'bones':
  8864. if( ! targetObject.skeleton ) {
  8865. console.error( ' can not bind to bones as node does not have a skeleton', this );
  8866. return;
  8867. }
  8868. // potential future optimization: skip this if propertyIndex is already an integer
  8869. // and convert the integer string to a true integer.
  8870. targetObject = targetObject.skeleton.bones;
  8871. // support resolving morphTarget names into indices.
  8872. for ( var i = 0; i < targetObject.length; i ++ ) {
  8873. if ( targetObject[i].name === objectIndex ) {
  8874. objectIndex = i;
  8875. break;
  8876. }
  8877. }
  8878. break;
  8879. default:
  8880. if ( targetObject[ objectName ] === undefined ) {
  8881. console.error( ' can not bind to objectName of node, undefined', this );
  8882. return;
  8883. }
  8884. targetObject = targetObject[ objectName ];
  8885. }
  8886. if ( objectIndex !== undefined ) {
  8887. if( targetObject[ objectIndex ] === undefined ) {
  8888. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  8889. return;
  8890. }
  8891. targetObject = targetObject[ objectIndex ];
  8892. }
  8893. }
  8894. // resolve property
  8895. var nodeProperty = targetObject[ propertyName ];
  8896. if ( ! nodeProperty ) {
  8897. var nodeName = parsedPath.nodeName;
  8898. console.error( " trying to update property for track: " + nodeName +
  8899. '.' + propertyName + " but it wasn't found.", targetObject );
  8900. return;
  8901. }
  8902. // determine versioning scheme
  8903. var versioning = this.Versioning.None;
  8904. if ( targetObject.needsUpdate !== undefined ) { // material
  8905. versioning = this.Versioning.NeedsUpdate;
  8906. this.targetObject = targetObject;
  8907. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  8908. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  8909. this.targetObject = targetObject;
  8910. }
  8911. // determine how the property gets bound
  8912. var bindingType = this.BindingType.Direct;
  8913. if ( propertyIndex !== undefined ) {
  8914. // access a sub element of the property array (only primitives are supported right now)
  8915. if ( propertyName === "morphTargetInfluences" ) {
  8916. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  8917. // support resolving morphTarget names into indices.
  8918. if ( ! targetObject.geometry ) {
  8919. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  8920. return;
  8921. }
  8922. if ( ! targetObject.geometry.morphTargets ) {
  8923. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  8924. return;
  8925. }
  8926. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  8927. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  8928. propertyIndex = i;
  8929. break;
  8930. }
  8931. }
  8932. }
  8933. bindingType = this.BindingType.ArrayElement;
  8934. this.resolvedProperty = nodeProperty;
  8935. this.propertyIndex = propertyIndex;
  8936. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  8937. // must use copy for Object3D.Euler/Quaternion
  8938. bindingType = this.BindingType.HasFromToArray;
  8939. this.resolvedProperty = nodeProperty;
  8940. } else if ( nodeProperty.length !== undefined ) {
  8941. bindingType = this.BindingType.EntireArray;
  8942. this.resolvedProperty = nodeProperty;
  8943. } else {
  8944. this.propertyName = propertyName;
  8945. }
  8946. // select getter / setter
  8947. this.getValue = this.GetterByBindingType[ bindingType ];
  8948. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  8949. },
  8950. unbind: function() {
  8951. this.node = null;
  8952. // back to the prototype version of getValue / setValue
  8953. // note: avoiding to mutate the shape of 'this' via 'delete'
  8954. this.getValue = this._getValue_unbound;
  8955. this.setValue = this._setValue_unbound;
  8956. }
  8957. };
  8958. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  8959. // these are used to "bind" a nonexistent property
  8960. _getValue_unavailable: function() {},
  8961. _setValue_unavailable: function() {},
  8962. // initial state of these methods that calls 'bind'
  8963. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  8964. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  8965. BindingType: {
  8966. Direct: 0,
  8967. EntireArray: 1,
  8968. ArrayElement: 2,
  8969. HasFromToArray: 3
  8970. },
  8971. Versioning: {
  8972. None: 0,
  8973. NeedsUpdate: 1,
  8974. MatrixWorldNeedsUpdate: 2
  8975. },
  8976. GetterByBindingType: [
  8977. function getValue_direct( buffer, offset ) {
  8978. buffer[ offset ] = this.node[ this.propertyName ];
  8979. },
  8980. function getValue_array( buffer, offset ) {
  8981. var source = this.resolvedProperty;
  8982. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  8983. buffer[ offset ++ ] = source[ i ];
  8984. }
  8985. },
  8986. function getValue_arrayElement( buffer, offset ) {
  8987. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  8988. },
  8989. function getValue_toArray( buffer, offset ) {
  8990. this.resolvedProperty.toArray( buffer, offset );
  8991. }
  8992. ],
  8993. SetterByBindingTypeAndVersioning: [
  8994. [
  8995. // Direct
  8996. function setValue_direct( buffer, offset ) {
  8997. this.node[ this.propertyName ] = buffer[ offset ];
  8998. },
  8999. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  9000. this.node[ this.propertyName ] = buffer[ offset ];
  9001. this.targetObject.needsUpdate = true;
  9002. },
  9003. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9004. this.node[ this.propertyName ] = buffer[ offset ];
  9005. this.targetObject.matrixWorldNeedsUpdate = true;
  9006. }
  9007. ], [
  9008. // EntireArray
  9009. function setValue_array( buffer, offset ) {
  9010. var dest = this.resolvedProperty;
  9011. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9012. dest[ i ] = buffer[ offset ++ ];
  9013. }
  9014. },
  9015. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9016. var dest = this.resolvedProperty;
  9017. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9018. dest[ i ] = buffer[ offset ++ ];
  9019. }
  9020. this.targetObject.needsUpdate = true;
  9021. },
  9022. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9023. var dest = this.resolvedProperty;
  9024. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9025. dest[ i ] = buffer[ offset ++ ];
  9026. }
  9027. this.targetObject.matrixWorldNeedsUpdate = true;
  9028. }
  9029. ], [
  9030. // ArrayElement
  9031. function setValue_arrayElement( buffer, offset ) {
  9032. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9033. },
  9034. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9035. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9036. this.targetObject.needsUpdate = true;
  9037. },
  9038. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9039. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9040. this.targetObject.matrixWorldNeedsUpdate = true;
  9041. }
  9042. ], [
  9043. // HasToFromArray
  9044. function setValue_fromArray( buffer, offset ) {
  9045. this.resolvedProperty.fromArray( buffer, offset );
  9046. },
  9047. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9048. this.resolvedProperty.fromArray( buffer, offset );
  9049. this.targetObject.needsUpdate = true;
  9050. },
  9051. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9052. this.resolvedProperty.fromArray( buffer, offset );
  9053. this.targetObject.matrixWorldNeedsUpdate = true;
  9054. }
  9055. ]
  9056. ]
  9057. } );
  9058. THREE.PropertyBinding.Composite =
  9059. function( targetGroup, path, optionalParsedPath ) {
  9060. var parsedPath = optionalParsedPath ||
  9061. THREE.PropertyBinding.parseTrackName( path );
  9062. this._targetGroup = targetGroup;
  9063. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9064. };
  9065. THREE.PropertyBinding.Composite.prototype = {
  9066. constructor: THREE.PropertyBinding.Composite,
  9067. getValue: function( array, offset ) {
  9068. this.bind(); // bind all binding
  9069. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9070. binding = this._bindings[ firstValidIndex ];
  9071. // and only call .getValue on the first
  9072. if ( binding !== undefined ) binding.getValue( array, offset );
  9073. },
  9074. setValue: function( array, offset ) {
  9075. var bindings = this._bindings;
  9076. for ( var i = this._targetGroup.nCachedObjects_,
  9077. n = bindings.length; i !== n; ++ i ) {
  9078. bindings[ i ].setValue( array, offset );
  9079. }
  9080. },
  9081. bind: function() {
  9082. var bindings = this._bindings;
  9083. for ( var i = this._targetGroup.nCachedObjects_,
  9084. n = bindings.length; i !== n; ++ i ) {
  9085. bindings[ i ].bind();
  9086. }
  9087. },
  9088. unbind: function() {
  9089. var bindings = this._bindings;
  9090. for ( var i = this._targetGroup.nCachedObjects_,
  9091. n = bindings.length; i !== n; ++ i ) {
  9092. bindings[ i ].unbind();
  9093. }
  9094. }
  9095. };
  9096. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9097. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9098. return new THREE.PropertyBinding( root, path, parsedPath );
  9099. } else {
  9100. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9101. }
  9102. };
  9103. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9104. // matches strings in the form of:
  9105. // nodeName.property
  9106. // nodeName.property[accessor]
  9107. // nodeName.material.property[accessor]
  9108. // uuid.property[accessor]
  9109. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9110. // parentName/nodeName.property
  9111. // parentName/parentName/nodeName.property[index]
  9112. // .bone[Armature.DEF_cog].position
  9113. // created and tested via https://regex101.com/#javascript
  9114. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9115. var matches = re.exec(trackName);
  9116. if( ! matches ) {
  9117. throw new Error( "cannot parse trackName at all: " + trackName );
  9118. }
  9119. if (matches.index === re.lastIndex) {
  9120. re.lastIndex++;
  9121. }
  9122. var results = {
  9123. // directoryName: matches[1], // (tschw) currently unused
  9124. nodeName: matches[3], // allowed to be null, specified root node.
  9125. objectName: matches[5],
  9126. objectIndex: matches[7],
  9127. propertyName: matches[9],
  9128. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9129. };
  9130. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9131. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9132. }
  9133. return results;
  9134. };
  9135. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9136. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9137. return root;
  9138. }
  9139. // search into skeleton bones.
  9140. if( root.skeleton ) {
  9141. var searchSkeleton = function( skeleton ) {
  9142. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9143. var bone = skeleton.bones[i];
  9144. if( bone.name === nodeName ) {
  9145. return bone;
  9146. }
  9147. }
  9148. return null;
  9149. };
  9150. var bone = searchSkeleton( root.skeleton );
  9151. if( bone ) {
  9152. return bone;
  9153. }
  9154. }
  9155. // search into node subtree.
  9156. if( root.children ) {
  9157. var searchNodeSubtree = function( children ) {
  9158. for( var i = 0; i < children.length; i ++ ) {
  9159. var childNode = children[i];
  9160. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9161. return childNode;
  9162. }
  9163. var result = searchNodeSubtree( childNode.children );
  9164. if( result ) return result;
  9165. }
  9166. return null;
  9167. };
  9168. var subTreeNode = searchNodeSubtree( root.children );
  9169. if( subTreeNode ) {
  9170. return subTreeNode;
  9171. }
  9172. }
  9173. return null;
  9174. }
  9175. // File:src/animation/PropertyMixer.js
  9176. /**
  9177. *
  9178. * Buffered scene graph property that allows weighted accumulation.
  9179. *
  9180. *
  9181. * @author Ben Houston / http://clara.io/
  9182. * @author David Sarno / http://lighthaus.us/
  9183. * @author tschw
  9184. */
  9185. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9186. this.binding = binding;
  9187. this.valueSize = valueSize;
  9188. var bufferType = Float64Array,
  9189. mixFunction;
  9190. switch ( typeName ) {
  9191. case 'quaternion': mixFunction = this._slerp; break;
  9192. case 'string':
  9193. case 'bool':
  9194. bufferType = Array, mixFunction = this._select; break;
  9195. default: mixFunction = this._lerp;
  9196. }
  9197. this.buffer = new bufferType( valueSize * 4 );
  9198. // layout: [ incoming | accu0 | accu1 | orig ]
  9199. //
  9200. // interpolators can use .buffer as their .result
  9201. // the data then goes to 'incoming'
  9202. //
  9203. // 'accu0' and 'accu1' are used frame-interleaved for
  9204. // the cumulative result and are compared to detect
  9205. // changes
  9206. //
  9207. // 'orig' stores the original state of the property
  9208. this._mixBufferRegion = mixFunction;
  9209. this.cumulativeWeight = 0;
  9210. this.useCount = 0;
  9211. this.referenceCount = 0;
  9212. };
  9213. THREE.PropertyMixer.prototype = {
  9214. constructor: THREE.PropertyMixer,
  9215. // accumulate data in the 'incoming' region into 'accu<i>'
  9216. accumulate: function( accuIndex, weight ) {
  9217. // note: happily accumulating nothing when weight = 0, the caller knows
  9218. // the weight and shouldn't have made the call in the first place
  9219. var buffer = this.buffer,
  9220. stride = this.valueSize,
  9221. offset = accuIndex * stride + stride,
  9222. currentWeight = this.cumulativeWeight;
  9223. if ( currentWeight === 0 ) {
  9224. // accuN := incoming * weight
  9225. for ( var i = 0; i !== stride; ++ i ) {
  9226. buffer[ offset + i ] = buffer[ i ];
  9227. }
  9228. currentWeight = weight;
  9229. } else {
  9230. // accuN := accuN + incoming * weight
  9231. currentWeight += weight;
  9232. var mix = weight / currentWeight;
  9233. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9234. }
  9235. this.cumulativeWeight = currentWeight;
  9236. },
  9237. // apply the state of 'accu<i>' to the binding when accus differ
  9238. apply: function( accuIndex ) {
  9239. var stride = this.valueSize,
  9240. buffer = this.buffer,
  9241. offset = accuIndex * stride + stride,
  9242. weight = this.cumulativeWeight,
  9243. binding = this.binding;
  9244. this.cumulativeWeight = 0;
  9245. if ( weight < 1 ) {
  9246. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9247. var originalValueOffset = stride * 3;
  9248. this._mixBufferRegion(
  9249. buffer, offset, originalValueOffset, 1 - weight, stride );
  9250. }
  9251. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9252. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9253. // value has changed -> update scene graph
  9254. binding.setValue( buffer, offset );
  9255. break;
  9256. }
  9257. }
  9258. },
  9259. // remember the state of the bound property and copy it to both accus
  9260. saveOriginalState: function() {
  9261. var binding = this.binding;
  9262. var buffer = this.buffer,
  9263. stride = this.valueSize,
  9264. originalValueOffset = stride * 3;
  9265. binding.getValue( buffer, originalValueOffset );
  9266. // accu[0..1] := orig -- initially detect changes against the original
  9267. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9268. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9269. }
  9270. this.cumulativeWeight = 0;
  9271. },
  9272. // apply the state previously taken via 'saveOriginalState' to the binding
  9273. restoreOriginalState: function() {
  9274. var originalValueOffset = this.valueSize * 3;
  9275. this.binding.setValue( this.buffer, originalValueOffset );
  9276. },
  9277. // mix functions
  9278. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9279. if ( t >= 0.5 ) {
  9280. for ( var i = 0; i !== stride; ++ i ) {
  9281. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9282. }
  9283. }
  9284. },
  9285. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9286. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9287. buffer, dstOffset, buffer, srcOffset, t );
  9288. },
  9289. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9290. var s = 1 - t;
  9291. for ( var i = 0; i !== stride; ++ i ) {
  9292. var j = dstOffset + i;
  9293. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9294. }
  9295. }
  9296. };
  9297. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9298. /**
  9299. *
  9300. * A Track of Boolean keyframe values.
  9301. *
  9302. *
  9303. * @author Ben Houston / http://clara.io/
  9304. * @author David Sarno / http://lighthaus.us/
  9305. * @author tschw
  9306. */
  9307. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9308. THREE.KeyframeTrack.call( this, name, times, values );
  9309. };
  9310. THREE.BooleanKeyframeTrack.prototype =
  9311. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9312. constructor: THREE.BooleanKeyframeTrack,
  9313. ValueTypeName: 'bool',
  9314. ValueBufferType: Array,
  9315. DefaultInterpolation: THREE.IntepolateDiscrete,
  9316. InterpolantFactoryMethodLinear: undefined,
  9317. InterpolantFactoryMethodSmooth: undefined
  9318. // Note: Actually this track could have a optimized / compressed
  9319. // representation of a single value and a custom interpolant that
  9320. // computes "firstValue ^ isOdd( index )".
  9321. } );
  9322. // File:src/animation/tracks/NumberKeyframeTrack.js
  9323. /**
  9324. *
  9325. * A Track of numeric keyframe values.
  9326. *
  9327. * @author Ben Houston / http://clara.io/
  9328. * @author David Sarno / http://lighthaus.us/
  9329. * @author tschw
  9330. */
  9331. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9332. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9333. };
  9334. THREE.NumberKeyframeTrack.prototype =
  9335. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9336. constructor: THREE.NumberKeyframeTrack,
  9337. ValueTypeName: 'number',
  9338. // ValueBufferType is inherited
  9339. // DefaultInterpolation is inherited
  9340. } );
  9341. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9342. /**
  9343. *
  9344. * A Track of quaternion keyframe values.
  9345. *
  9346. * @author Ben Houston / http://clara.io/
  9347. * @author David Sarno / http://lighthaus.us/
  9348. * @author tschw
  9349. */
  9350. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9351. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9352. };
  9353. THREE.QuaternionKeyframeTrack.prototype =
  9354. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9355. constructor: THREE.QuaternionKeyframeTrack,
  9356. ValueTypeName: 'quaternion',
  9357. // ValueBufferType is inherited
  9358. DefaultInterpolation: THREE.InterpolateLinear,
  9359. InterpolantFactoryMethodLinear: function( result ) {
  9360. return new THREE.QuaternionLinearInterpolant(
  9361. this.times, this.values, this.getValueSize(), result );
  9362. },
  9363. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9364. } );
  9365. // File:src/animation/tracks/StringKeyframeTrack.js
  9366. /**
  9367. *
  9368. * A Track that interpolates Strings
  9369. *
  9370. *
  9371. * @author Ben Houston / http://clara.io/
  9372. * @author David Sarno / http://lighthaus.us/
  9373. * @author tschw
  9374. */
  9375. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9376. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9377. };
  9378. THREE.StringKeyframeTrack.prototype =
  9379. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9380. constructor: THREE.StringKeyframeTrack,
  9381. ValueTypeName: 'string',
  9382. ValueBufferType: Array,
  9383. DefaultInterpolation: THREE.IntepolateDiscrete,
  9384. InterpolantFactoryMethodLinear: undefined,
  9385. InterpolantFactoryMethodSmooth: undefined
  9386. } );
  9387. // File:src/animation/tracks/VectorKeyframeTrack.js
  9388. /**
  9389. *
  9390. * A Track of vectored keyframe values.
  9391. *
  9392. *
  9393. * @author Ben Houston / http://clara.io/
  9394. * @author David Sarno / http://lighthaus.us/
  9395. * @author tschw
  9396. */
  9397. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9398. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9399. };
  9400. THREE.VectorKeyframeTrack.prototype =
  9401. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9402. constructor: THREE.VectorKeyframeTrack,
  9403. ValueTypeName: 'vector'
  9404. // ValueBufferType is inherited
  9405. // DefaultInterpolation is inherited
  9406. } );
  9407. // File:src/audio/Audio.js
  9408. /**
  9409. * @author mrdoob / http://mrdoob.com/
  9410. */
  9411. THREE.Audio = function ( listener ) {
  9412. THREE.Object3D.call( this );
  9413. this.type = 'Audio';
  9414. this.context = listener.context;
  9415. this.source = this.context.createBufferSource();
  9416. this.source.onended = this.onEnded.bind( this );
  9417. this.gain = this.context.createGain();
  9418. this.gain.connect( this.context.destination );
  9419. this.panner = this.context.createPanner();
  9420. this.panner.connect( this.gain );
  9421. this.autoplay = false;
  9422. this.startTime = 0;
  9423. this.playbackRate = 1;
  9424. this.isPlaying = false;
  9425. };
  9426. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9427. THREE.Audio.prototype.constructor = THREE.Audio;
  9428. THREE.Audio.prototype.load = function ( file ) {
  9429. var scope = this;
  9430. var request = new XMLHttpRequest();
  9431. request.open( 'GET', file, true );
  9432. request.responseType = 'arraybuffer';
  9433. request.onload = function ( e ) {
  9434. scope.context.decodeAudioData( this.response, function ( buffer ) {
  9435. scope.source.buffer = buffer;
  9436. if ( scope.autoplay ) scope.play();
  9437. } );
  9438. };
  9439. request.send();
  9440. return this;
  9441. };
  9442. THREE.Audio.prototype.play = function () {
  9443. if ( this.isPlaying === true ) {
  9444. console.warn( 'THREE.Audio: Audio is already playing.' );
  9445. return;
  9446. }
  9447. var source = this.context.createBufferSource();
  9448. source.buffer = this.source.buffer;
  9449. source.loop = this.source.loop;
  9450. source.onended = this.source.onended;
  9451. source.start( 0, this.startTime );
  9452. source.playbackRate.value = this.playbackRate;
  9453. this.isPlaying = true;
  9454. this.source = source;
  9455. this.connect();
  9456. };
  9457. THREE.Audio.prototype.pause = function () {
  9458. this.source.stop();
  9459. this.startTime = this.context.currentTime;
  9460. };
  9461. THREE.Audio.prototype.stop = function () {
  9462. this.source.stop();
  9463. this.startTime = 0;
  9464. };
  9465. THREE.Audio.prototype.connect = function () {
  9466. if ( this.filter !== undefined ) {
  9467. this.source.connect( this.filter );
  9468. this.filter.connect( this.panner );
  9469. } else {
  9470. this.source.connect( this.panner );
  9471. }
  9472. };
  9473. THREE.Audio.prototype.disconnect = function () {
  9474. if ( this.filter !== undefined ) {
  9475. this.source.disconnect( this.filter );
  9476. this.filter.disconnect( this.panner );
  9477. } else {
  9478. this.source.disconnect( this.panner );
  9479. }
  9480. };
  9481. THREE.Audio.prototype.setFilter = function ( value ) {
  9482. if ( this.isPlaying === true ) {
  9483. this.disconnect();
  9484. this.filter = value;
  9485. this.connect();
  9486. } else {
  9487. this.filter = value;
  9488. }
  9489. };
  9490. THREE.Audio.prototype.getFilter = function () {
  9491. return this.filter;
  9492. };
  9493. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9494. this.playbackRate = value;
  9495. if ( this.isPlaying === true ) {
  9496. this.source.playbackRate.value = this.playbackRate;
  9497. }
  9498. };
  9499. THREE.Audio.prototype.getPlaybackRate = function () {
  9500. return this.playbackRate;
  9501. };
  9502. THREE.Audio.prototype.onEnded = function() {
  9503. this.isPlaying = false;
  9504. };
  9505. THREE.Audio.prototype.setLoop = function ( value ) {
  9506. this.source.loop = value;
  9507. };
  9508. THREE.Audio.prototype.getLoop = function () {
  9509. return this.source.loop;
  9510. };
  9511. THREE.Audio.prototype.setRefDistance = function ( value ) {
  9512. this.panner.refDistance = value;
  9513. };
  9514. THREE.Audio.prototype.getRefDistance = function () {
  9515. return this.panner.refDistance;
  9516. };
  9517. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  9518. this.panner.rolloffFactor = value;
  9519. };
  9520. THREE.Audio.prototype.getRolloffFactor = function () {
  9521. return this.panner.rolloffFactor;
  9522. };
  9523. THREE.Audio.prototype.setVolume = function ( value ) {
  9524. this.gain.gain.value = value;
  9525. };
  9526. THREE.Audio.prototype.getVolume = function () {
  9527. return this.gain.gain.value;
  9528. };
  9529. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  9530. var position = new THREE.Vector3();
  9531. return function updateMatrixWorld( force ) {
  9532. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9533. position.setFromMatrixPosition( this.matrixWorld );
  9534. this.panner.setPosition( position.x, position.y, position.z );
  9535. };
  9536. } )();
  9537. // File:src/audio/AudioListener.js
  9538. /**
  9539. * @author mrdoob / http://mrdoob.com/
  9540. */
  9541. THREE.AudioListener = function () {
  9542. THREE.Object3D.call( this );
  9543. this.type = 'AudioListener';
  9544. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  9545. };
  9546. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9547. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9548. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9549. var position = new THREE.Vector3();
  9550. var quaternion = new THREE.Quaternion();
  9551. var scale = new THREE.Vector3();
  9552. var orientation = new THREE.Vector3();
  9553. return function updateMatrixWorld( force ) {
  9554. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9555. var listener = this.context.listener;
  9556. var up = this.up;
  9557. this.matrixWorld.decompose( position, quaternion, scale );
  9558. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9559. listener.setPosition( position.x, position.y, position.z );
  9560. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9561. };
  9562. } )();
  9563. // File:src/cameras/Camera.js
  9564. /**
  9565. * @author mrdoob / http://mrdoob.com/
  9566. * @author mikael emtinger / http://gomo.se/
  9567. * @author WestLangley / http://github.com/WestLangley
  9568. */
  9569. THREE.Camera = function () {
  9570. THREE.Object3D.call( this );
  9571. this.type = 'Camera';
  9572. this.matrixWorldInverse = new THREE.Matrix4();
  9573. this.projectionMatrix = new THREE.Matrix4();
  9574. };
  9575. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9576. THREE.Camera.prototype.constructor = THREE.Camera;
  9577. THREE.Camera.prototype.getWorldDirection = function () {
  9578. var quaternion = new THREE.Quaternion();
  9579. return function ( optionalTarget ) {
  9580. var result = optionalTarget || new THREE.Vector3();
  9581. this.getWorldQuaternion( quaternion );
  9582. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9583. };
  9584. }();
  9585. THREE.Camera.prototype.lookAt = function () {
  9586. // This routine does not support cameras with rotated and/or translated parent(s)
  9587. var m1 = new THREE.Matrix4();
  9588. return function ( vector ) {
  9589. m1.lookAt( this.position, vector, this.up );
  9590. this.quaternion.setFromRotationMatrix( m1 );
  9591. };
  9592. }();
  9593. THREE.Camera.prototype.clone = function () {
  9594. return new this.constructor().copy( this );
  9595. };
  9596. THREE.Camera.prototype.copy = function ( source ) {
  9597. THREE.Object3D.prototype.copy.call( this, source );
  9598. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9599. this.projectionMatrix.copy( source.projectionMatrix );
  9600. return this;
  9601. };
  9602. // File:src/cameras/CubeCamera.js
  9603. /**
  9604. * Camera for rendering cube maps
  9605. * - renders scene into axis-aligned cube
  9606. *
  9607. * @author alteredq / http://alteredqualia.com/
  9608. */
  9609. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9610. THREE.Object3D.call( this );
  9611. this.type = 'CubeCamera';
  9612. var fov = 90, aspect = 1;
  9613. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9614. cameraPX.up.set( 0, - 1, 0 );
  9615. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9616. this.add( cameraPX );
  9617. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9618. cameraNX.up.set( 0, - 1, 0 );
  9619. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9620. this.add( cameraNX );
  9621. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9622. cameraPY.up.set( 0, 0, 1 );
  9623. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9624. this.add( cameraPY );
  9625. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9626. cameraNY.up.set( 0, 0, - 1 );
  9627. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9628. this.add( cameraNY );
  9629. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9630. cameraPZ.up.set( 0, - 1, 0 );
  9631. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9632. this.add( cameraPZ );
  9633. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9634. cameraNZ.up.set( 0, - 1, 0 );
  9635. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9636. this.add( cameraNZ );
  9637. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  9638. this.updateCubeMap = function ( renderer, scene ) {
  9639. if ( this.parent === null ) this.updateMatrixWorld();
  9640. var renderTarget = this.renderTarget;
  9641. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9642. renderTarget.texture.generateMipmaps = false;
  9643. renderTarget.activeCubeFace = 0;
  9644. renderer.render( scene, cameraPX, renderTarget );
  9645. renderTarget.activeCubeFace = 1;
  9646. renderer.render( scene, cameraNX, renderTarget );
  9647. renderTarget.activeCubeFace = 2;
  9648. renderer.render( scene, cameraPY, renderTarget );
  9649. renderTarget.activeCubeFace = 3;
  9650. renderer.render( scene, cameraNY, renderTarget );
  9651. renderTarget.activeCubeFace = 4;
  9652. renderer.render( scene, cameraPZ, renderTarget );
  9653. renderTarget.texture.generateMipmaps = generateMipmaps;
  9654. renderTarget.activeCubeFace = 5;
  9655. renderer.render( scene, cameraNZ, renderTarget );
  9656. renderer.setRenderTarget( null );
  9657. };
  9658. };
  9659. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9660. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9661. // File:src/cameras/OrthographicCamera.js
  9662. /**
  9663. * @author alteredq / http://alteredqualia.com/
  9664. */
  9665. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9666. THREE.Camera.call( this );
  9667. this.type = 'OrthographicCamera';
  9668. this.zoom = 1;
  9669. this.left = left;
  9670. this.right = right;
  9671. this.top = top;
  9672. this.bottom = bottom;
  9673. this.near = ( near !== undefined ) ? near : 0.1;
  9674. this.far = ( far !== undefined ) ? far : 2000;
  9675. this.updateProjectionMatrix();
  9676. };
  9677. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9678. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9679. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9680. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9681. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9682. var cx = ( this.right + this.left ) / 2;
  9683. var cy = ( this.top + this.bottom ) / 2;
  9684. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9685. };
  9686. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9687. THREE.Camera.prototype.copy.call( this, source );
  9688. this.left = source.left;
  9689. this.right = source.right;
  9690. this.top = source.top;
  9691. this.bottom = source.bottom;
  9692. this.near = source.near;
  9693. this.far = source.far;
  9694. this.zoom = source.zoom;
  9695. return this;
  9696. };
  9697. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9698. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9699. data.object.zoom = this.zoom;
  9700. data.object.left = this.left;
  9701. data.object.right = this.right;
  9702. data.object.top = this.top;
  9703. data.object.bottom = this.bottom;
  9704. data.object.near = this.near;
  9705. data.object.far = this.far;
  9706. return data;
  9707. };
  9708. // File:src/cameras/PerspectiveCamera.js
  9709. /**
  9710. * @author mrdoob / http://mrdoob.com/
  9711. * @author greggman / http://games.greggman.com/
  9712. * @author zz85 / http://www.lab4games.net/zz85/blog
  9713. */
  9714. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  9715. THREE.Camera.call( this );
  9716. this.type = 'PerspectiveCamera';
  9717. this.zoom = 1;
  9718. this.fov = fov !== undefined ? fov : 50;
  9719. this.aspect = aspect !== undefined ? aspect : 1;
  9720. this.near = near !== undefined ? near : 0.1;
  9721. this.far = far !== undefined ? far : 2000;
  9722. this.updateProjectionMatrix();
  9723. };
  9724. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  9725. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  9726. /**
  9727. * Uses Focal Length (in mm) to estimate and set FOV
  9728. * 35mm (full-frame) camera is used if frame size is not specified;
  9729. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  9730. */
  9731. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  9732. if ( frameHeight === undefined ) frameHeight = 24;
  9733. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  9734. this.updateProjectionMatrix();
  9735. };
  9736. /**
  9737. * Sets an offset in a larger frustum. This is useful for multi-window or
  9738. * multi-monitor/multi-machine setups.
  9739. *
  9740. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9741. * the monitors are in grid like this
  9742. *
  9743. * +---+---+---+
  9744. * | A | B | C |
  9745. * +---+---+---+
  9746. * | D | E | F |
  9747. * +---+---+---+
  9748. *
  9749. * then for each monitor you would call it like this
  9750. *
  9751. * var w = 1920;
  9752. * var h = 1080;
  9753. * var fullWidth = w * 3;
  9754. * var fullHeight = h * 2;
  9755. *
  9756. * --A--
  9757. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9758. * --B--
  9759. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9760. * --C--
  9761. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9762. * --D--
  9763. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9764. * --E--
  9765. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9766. * --F--
  9767. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9768. *
  9769. * Note there is no reason monitors have to be the same size or in a grid.
  9770. */
  9771. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  9772. this.fullWidth = fullWidth;
  9773. this.fullHeight = fullHeight;
  9774. this.x = x;
  9775. this.y = y;
  9776. this.width = width;
  9777. this.height = height;
  9778. this.updateProjectionMatrix();
  9779. };
  9780. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  9781. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  9782. if ( this.fullWidth ) {
  9783. var aspect = this.fullWidth / this.fullHeight;
  9784. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  9785. var bottom = - top;
  9786. var left = aspect * bottom;
  9787. var right = aspect * top;
  9788. var width = Math.abs( right - left );
  9789. var height = Math.abs( top - bottom );
  9790. this.projectionMatrix.makeFrustum(
  9791. left + this.x * width / this.fullWidth,
  9792. left + ( this.x + this.width ) * width / this.fullWidth,
  9793. top - ( this.y + this.height ) * height / this.fullHeight,
  9794. top - this.y * height / this.fullHeight,
  9795. this.near,
  9796. this.far
  9797. );
  9798. } else {
  9799. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  9800. }
  9801. };
  9802. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  9803. THREE.Camera.prototype.copy.call( this, source );
  9804. this.fov = source.fov;
  9805. this.aspect = source.aspect;
  9806. this.near = source.near;
  9807. this.far = source.far;
  9808. this.zoom = source.zoom;
  9809. return this;
  9810. };
  9811. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  9812. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9813. data.object.zoom = this.zoom;
  9814. data.object.fov = this.fov;
  9815. data.object.aspect = this.aspect;
  9816. data.object.near = this.near;
  9817. data.object.far = this.far;
  9818. return data;
  9819. };
  9820. // File:src/lights/Light.js
  9821. /**
  9822. * @author mrdoob / http://mrdoob.com/
  9823. * @author alteredq / http://alteredqualia.com/
  9824. */
  9825. THREE.Light = function ( color ) {
  9826. THREE.Object3D.call( this );
  9827. this.type = 'Light';
  9828. this.color = new THREE.Color( color );
  9829. this.receiveShadow = undefined;
  9830. };
  9831. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  9832. THREE.Light.prototype.constructor = THREE.Light;
  9833. THREE.Light.prototype.copy = function ( source ) {
  9834. THREE.Object3D.prototype.copy.call( this, source );
  9835. this.color.copy( source.color );
  9836. return this;
  9837. };
  9838. THREE.Light.prototype.toJSON = function ( meta ) {
  9839. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9840. data.object.color = this.color.getHex();
  9841. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  9842. if ( this.intensity !== undefined ) data.object.intensity = this.intensity;
  9843. if ( this.distance !== undefined ) data.object.distance = this.distance;
  9844. if ( this.angle !== undefined ) data.object.angle = this.angle;
  9845. if ( this.decay !== undefined ) data.object.decay = this.decay;
  9846. if ( this.exponent !== undefined ) data.object.exponent = this.exponent;
  9847. return data;
  9848. };
  9849. // File:src/lights/LightShadow.js
  9850. /**
  9851. * @author mrdoob / http://mrdoob.com/
  9852. */
  9853. THREE.LightShadow = function ( camera ) {
  9854. this.camera = camera;
  9855. this.bias = 0;
  9856. this.darkness = 1;
  9857. this.mapSize = new THREE.Vector2( 512, 512 );
  9858. this.map = null;
  9859. this.matrix = null;
  9860. };
  9861. THREE.LightShadow.prototype = {
  9862. constructor: THREE.LightShadow,
  9863. copy: function ( source ) {
  9864. this.camera = source.camera.clone();
  9865. this.bias = source.bias;
  9866. this.darkness = source.darkness;
  9867. this.mapSize.copy( source.mapSize );
  9868. return this;
  9869. },
  9870. clone: function () {
  9871. return new this.constructor().copy( this );
  9872. }
  9873. };
  9874. // File:src/lights/AmbientLight.js
  9875. /**
  9876. * @author mrdoob / http://mrdoob.com/
  9877. */
  9878. THREE.AmbientLight = function ( color ) {
  9879. THREE.Light.call( this, color );
  9880. this.type = 'AmbientLight';
  9881. this.castShadow = undefined;
  9882. };
  9883. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  9884. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  9885. // File:src/lights/DirectionalLight.js
  9886. /**
  9887. * @author mrdoob / http://mrdoob.com/
  9888. * @author alteredq / http://alteredqualia.com/
  9889. */
  9890. THREE.DirectionalLight = function ( color, intensity ) {
  9891. THREE.Light.call( this, color );
  9892. this.type = 'DirectionalLight';
  9893. this.position.set( 0, 1, 0 );
  9894. this.updateMatrix();
  9895. this.target = new THREE.Object3D();
  9896. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9897. this.shadow = new THREE.LightShadow( new THREE.OrthographicCamera( - 500, 500, 500, - 500, 50, 5000 ) );
  9898. };
  9899. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  9900. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  9901. THREE.DirectionalLight.prototype.copy = function ( source ) {
  9902. THREE.Light.prototype.copy.call( this, source );
  9903. this.intensity = source.intensity;
  9904. this.target = source.target.clone();
  9905. this.shadow = source.shadow.clone();
  9906. return this;
  9907. };
  9908. // File:src/lights/HemisphereLight.js
  9909. /**
  9910. * @author alteredq / http://alteredqualia.com/
  9911. */
  9912. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  9913. THREE.Light.call( this, skyColor );
  9914. this.type = 'HemisphereLight';
  9915. this.castShadow = undefined;
  9916. this.position.set( 0, 1, 0 );
  9917. this.updateMatrix();
  9918. this.groundColor = new THREE.Color( groundColor );
  9919. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9920. };
  9921. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  9922. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  9923. THREE.HemisphereLight.prototype.copy = function ( source ) {
  9924. THREE.Light.prototype.copy.call( this, source );
  9925. this.groundColor.copy( source.groundColor );
  9926. this.intensity = source.intensity;
  9927. return this;
  9928. };
  9929. // File:src/lights/PointLight.js
  9930. /**
  9931. * @author mrdoob / http://mrdoob.com/
  9932. */
  9933. THREE.PointLight = function ( color, intensity, distance, decay ) {
  9934. THREE.Light.call( this, color );
  9935. this.type = 'PointLight';
  9936. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9937. this.distance = ( distance !== undefined ) ? distance : 0;
  9938. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  9939. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 1, 500 ) );
  9940. };
  9941. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  9942. THREE.PointLight.prototype.constructor = THREE.PointLight;
  9943. THREE.PointLight.prototype.copy = function ( source ) {
  9944. THREE.Light.prototype.copy.call( this, source );
  9945. this.intensity = source.intensity;
  9946. this.distance = source.distance;
  9947. this.decay = source.decay;
  9948. this.shadow = source.shadow.clone();
  9949. return this;
  9950. };
  9951. // File:src/lights/SpotLight.js
  9952. /**
  9953. * @author alteredq / http://alteredqualia.com/
  9954. */
  9955. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  9956. THREE.Light.call( this, color );
  9957. this.type = 'SpotLight';
  9958. this.position.set( 0, 1, 0 );
  9959. this.updateMatrix();
  9960. this.target = new THREE.Object3D();
  9961. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9962. this.distance = ( distance !== undefined ) ? distance : 0;
  9963. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  9964. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  9965. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  9966. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 50, 1, 50, 5000 ) );
  9967. };
  9968. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  9969. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  9970. THREE.SpotLight.prototype.copy = function ( source ) {
  9971. THREE.Light.prototype.copy.call( this, source );
  9972. this.intensity = source.intensity;
  9973. this.distance = source.distance;
  9974. this.angle = source.angle;
  9975. this.exponent = source.exponent;
  9976. this.decay = source.decay;
  9977. this.target = source.target.clone();
  9978. this.shadow = source.shadow.clone();
  9979. return this;
  9980. };
  9981. // File:src/loaders/Cache.js
  9982. /**
  9983. * @author mrdoob / http://mrdoob.com/
  9984. */
  9985. THREE.Cache = {
  9986. enabled: false,
  9987. files: {},
  9988. add: function ( key, file ) {
  9989. if ( this.enabled === false ) return;
  9990. // console.log( 'THREE.Cache', 'Adding key:', key );
  9991. this.files[ key ] = file;
  9992. },
  9993. get: function ( key ) {
  9994. if ( this.enabled === false ) return;
  9995. // console.log( 'THREE.Cache', 'Checking key:', key );
  9996. return this.files[ key ];
  9997. },
  9998. remove: function ( key ) {
  9999. delete this.files[ key ];
  10000. },
  10001. clear: function () {
  10002. this.files = {};
  10003. }
  10004. };
  10005. // File:src/loaders/Loader.js
  10006. /**
  10007. * @author alteredq / http://alteredqualia.com/
  10008. */
  10009. THREE.Loader = function () {
  10010. this.onLoadStart = function () {};
  10011. this.onLoadProgress = function () {};
  10012. this.onLoadComplete = function () {};
  10013. };
  10014. THREE.Loader.prototype = {
  10015. constructor: THREE.Loader,
  10016. crossOrigin: undefined,
  10017. extractUrlBase: function ( url ) {
  10018. var parts = url.split( '/' );
  10019. if ( parts.length === 1 ) return './';
  10020. parts.pop();
  10021. return parts.join( '/' ) + '/';
  10022. },
  10023. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10024. var array = [];
  10025. for ( var i = 0; i < materials.length; ++ i ) {
  10026. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10027. }
  10028. return array;
  10029. },
  10030. createMaterial: ( function () {
  10031. var color, textureLoader, materialLoader;
  10032. return function ( m, texturePath, crossOrigin ) {
  10033. if ( color === undefined ) color = new THREE.Color();
  10034. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10035. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10036. // convert from old material format
  10037. var textures = {};
  10038. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10039. var fullPath = texturePath + path;
  10040. var loader = THREE.Loader.Handlers.get( fullPath );
  10041. var texture;
  10042. if ( loader !== null ) {
  10043. texture = loader.load( fullPath );
  10044. } else {
  10045. textureLoader.setCrossOrigin( crossOrigin );
  10046. texture = textureLoader.load( fullPath );
  10047. }
  10048. if ( repeat !== undefined ) {
  10049. texture.repeat.fromArray( repeat );
  10050. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10051. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10052. }
  10053. if ( offset !== undefined ) {
  10054. texture.offset.fromArray( offset );
  10055. }
  10056. if ( wrap !== undefined ) {
  10057. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10058. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10059. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10060. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10061. }
  10062. if ( anisotropy !== undefined ) {
  10063. texture.anisotropy = anisotropy;
  10064. }
  10065. var uuid = THREE.Math.generateUUID();
  10066. textures[ uuid ] = texture;
  10067. return uuid;
  10068. }
  10069. //
  10070. var json = {
  10071. uuid: THREE.Math.generateUUID(),
  10072. type: 'MeshLambertMaterial'
  10073. };
  10074. for ( var name in m ) {
  10075. var value = m[ name ];
  10076. switch ( name ) {
  10077. case 'DbgColor':
  10078. case 'DbgIndex':
  10079. case 'opticalDensity':
  10080. case 'illumination':
  10081. break;
  10082. case 'DbgName':
  10083. json.name = value;
  10084. break;
  10085. case 'blending':
  10086. json.blending = THREE[ value ];
  10087. break;
  10088. case 'colorAmbient':
  10089. console.warn( 'THREE.Loader.createMaterial: colorAmbient is no longer supported' );
  10090. break;
  10091. case 'colorDiffuse':
  10092. json.color = color.fromArray( value ).getHex();
  10093. break;
  10094. case 'colorSpecular':
  10095. json.specular = color.fromArray( value ).getHex();
  10096. break;
  10097. case 'colorEmissive':
  10098. json.emissive = color.fromArray( value ).getHex();
  10099. break;
  10100. case 'specularCoef':
  10101. json.shininess = value;
  10102. break;
  10103. case 'shading':
  10104. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10105. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10106. break;
  10107. case 'mapDiffuse':
  10108. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10109. break;
  10110. case 'mapDiffuseRepeat':
  10111. case 'mapDiffuseOffset':
  10112. case 'mapDiffuseWrap':
  10113. case 'mapDiffuseAnisotropy':
  10114. break;
  10115. case 'mapLight':
  10116. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10117. break;
  10118. case 'mapLightRepeat':
  10119. case 'mapLightOffset':
  10120. case 'mapLightWrap':
  10121. case 'mapLightAnisotropy':
  10122. break;
  10123. case 'mapAO':
  10124. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10125. break;
  10126. case 'mapAORepeat':
  10127. case 'mapAOOffset':
  10128. case 'mapAOWrap':
  10129. case 'mapAOAnisotropy':
  10130. break;
  10131. case 'mapBump':
  10132. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10133. break;
  10134. case 'mapBumpScale':
  10135. json.bumpScale = value;
  10136. break;
  10137. case 'mapBumpRepeat':
  10138. case 'mapBumpOffset':
  10139. case 'mapBumpWrap':
  10140. case 'mapBumpAnisotropy':
  10141. break;
  10142. case 'mapNormal':
  10143. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10144. break;
  10145. case 'mapNormalFactor':
  10146. json.normalScale = [ value, value ];
  10147. break;
  10148. case 'mapNormalRepeat':
  10149. case 'mapNormalOffset':
  10150. case 'mapNormalWrap':
  10151. case 'mapNormalAnisotropy':
  10152. break;
  10153. case 'mapSpecular':
  10154. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10155. break;
  10156. case 'mapSpecularRepeat':
  10157. case 'mapSpecularOffset':
  10158. case 'mapSpecularWrap':
  10159. case 'mapSpecularAnisotropy':
  10160. break;
  10161. case 'mapAlpha':
  10162. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10163. break;
  10164. case 'mapAlphaRepeat':
  10165. case 'mapAlphaOffset':
  10166. case 'mapAlphaWrap':
  10167. case 'mapAlphaAnisotropy':
  10168. break;
  10169. case 'flipSided':
  10170. json.side = THREE.BackSide;
  10171. break;
  10172. case 'doubleSided':
  10173. json.side = THREE.DoubleSide;
  10174. break;
  10175. case 'transparency':
  10176. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10177. json.opacity = value;
  10178. break;
  10179. case 'opacity':
  10180. case 'transparent':
  10181. case 'depthTest':
  10182. case 'depthWrite':
  10183. case 'transparent':
  10184. case 'visible':
  10185. case 'wireframe':
  10186. json[ name ] = value;
  10187. break;
  10188. case 'vertexColors':
  10189. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10190. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10191. break;
  10192. default:
  10193. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10194. break;
  10195. }
  10196. }
  10197. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10198. if ( json.opacity < 1 ) json.transparent = true;
  10199. materialLoader.setTextures( textures );
  10200. return materialLoader.parse( json );
  10201. };
  10202. } )()
  10203. };
  10204. THREE.Loader.Handlers = {
  10205. handlers: [],
  10206. add: function ( regex, loader ) {
  10207. this.handlers.push( regex, loader );
  10208. },
  10209. get: function ( file ) {
  10210. var handlers = this.handlers;
  10211. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10212. var regex = handlers[ i ];
  10213. var loader = handlers[ i + 1 ];
  10214. if ( regex.test( file ) ) {
  10215. return loader;
  10216. }
  10217. }
  10218. return null;
  10219. }
  10220. };
  10221. // File:src/loaders/XHRLoader.js
  10222. /**
  10223. * @author mrdoob / http://mrdoob.com/
  10224. */
  10225. THREE.XHRLoader = function ( manager ) {
  10226. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10227. };
  10228. THREE.XHRLoader.prototype = {
  10229. constructor: THREE.XHRLoader,
  10230. load: function ( url, onLoad, onProgress, onError ) {
  10231. if ( this.path !== undefined ) url = this.path + url;
  10232. var scope = this;
  10233. var cached = THREE.Cache.get( url );
  10234. if ( cached !== undefined ) {
  10235. if ( onLoad ) {
  10236. setTimeout( function () {
  10237. onLoad( cached );
  10238. }, 0 );
  10239. }
  10240. return cached;
  10241. }
  10242. var request = new XMLHttpRequest();
  10243. request.overrideMimeType( 'text/plain' );
  10244. request.open( 'GET', url, true );
  10245. request.addEventListener( 'load', function ( event ) {
  10246. var response = event.target.response;
  10247. THREE.Cache.add( url, response );
  10248. if ( this.status === 200 && this.readyState === 4 ) {
  10249. if ( onLoad ) onLoad( response );
  10250. scope.manager.itemEnd( url );
  10251. } else {
  10252. if ( onError ) onError( event );
  10253. scope.manager.itemError( url );
  10254. }
  10255. }, false );
  10256. if ( onProgress !== undefined ) {
  10257. request.addEventListener( 'progress', function ( event ) {
  10258. onProgress( event );
  10259. }, false );
  10260. }
  10261. request.addEventListener( 'error', function ( event ) {
  10262. if ( onError ) onError( event );
  10263. scope.manager.itemError( url );
  10264. }, false );
  10265. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  10266. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10267. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10268. request.send( null );
  10269. scope.manager.itemStart( url );
  10270. return request;
  10271. },
  10272. setCrossOrigin: function ( value ) {
  10273. this.crossOrigin = value;
  10274. },
  10275. setResponseType: function ( value ) {
  10276. this.responseType = value;
  10277. },
  10278. setPath: function ( value ) {
  10279. this.path = value;
  10280. },
  10281. setWithCredentials: function ( value ) {
  10282. this.withCredentials = value;
  10283. }
  10284. };
  10285. // File:src/loaders/ImageLoader.js
  10286. /**
  10287. * @author mrdoob / http://mrdoob.com/
  10288. */
  10289. THREE.ImageLoader = function ( manager ) {
  10290. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10291. };
  10292. THREE.ImageLoader.prototype = {
  10293. constructor: THREE.ImageLoader,
  10294. load: function ( url, onLoad, onProgress, onError ) {
  10295. if ( this.path !== undefined ) url = this.path + url;
  10296. var scope = this;
  10297. var cached = THREE.Cache.get( url );
  10298. if ( cached !== undefined ) {
  10299. scope.manager.itemStart( url );
  10300. if ( onLoad ) {
  10301. setTimeout( function () {
  10302. onLoad( cached );
  10303. scope.manager.itemEnd( url );
  10304. }, 0 );
  10305. } else {
  10306. scope.manager.itemEnd( url );
  10307. }
  10308. return cached;
  10309. }
  10310. var image = document.createElement( 'img' );
  10311. image.addEventListener( 'load', function ( event ) {
  10312. THREE.Cache.add( url, this );
  10313. if ( onLoad ) onLoad( this );
  10314. scope.manager.itemEnd( url );
  10315. }, false );
  10316. if ( onProgress !== undefined ) {
  10317. image.addEventListener( 'progress', function ( event ) {
  10318. onProgress( event );
  10319. }, false );
  10320. }
  10321. image.addEventListener( 'error', function ( event ) {
  10322. if ( onError ) onError( event );
  10323. scope.manager.itemError( url );
  10324. }, false );
  10325. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10326. scope.manager.itemStart( url );
  10327. image.src = url;
  10328. return image;
  10329. },
  10330. setCrossOrigin: function ( value ) {
  10331. this.crossOrigin = value;
  10332. },
  10333. setPath: function ( value ) {
  10334. this.path = value;
  10335. }
  10336. };
  10337. // File:src/loaders/JSONLoader.js
  10338. /**
  10339. * @author mrdoob / http://mrdoob.com/
  10340. * @author alteredq / http://alteredqualia.com/
  10341. */
  10342. THREE.JSONLoader = function ( manager ) {
  10343. if ( typeof manager === 'boolean' ) {
  10344. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10345. manager = undefined;
  10346. }
  10347. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10348. this.withCredentials = false;
  10349. };
  10350. THREE.JSONLoader.prototype = {
  10351. constructor: THREE.JSONLoader,
  10352. // Deprecated
  10353. get statusDomElement () {
  10354. if ( this._statusDomElement === undefined ) {
  10355. this._statusDomElement = document.createElement( 'div' );
  10356. }
  10357. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10358. return this._statusDomElement;
  10359. },
  10360. load: function( url, onLoad, onProgress, onError ) {
  10361. var scope = this;
  10362. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10363. var loader = new THREE.XHRLoader( this.manager );
  10364. loader.setCrossOrigin( this.crossOrigin );
  10365. loader.setWithCredentials( this.withCredentials );
  10366. loader.load( url, function ( text ) {
  10367. var json = JSON.parse( text );
  10368. var metadata = json.metadata;
  10369. if ( metadata !== undefined ) {
  10370. var type = metadata.type;
  10371. if ( type !== undefined ) {
  10372. if ( type.toLowerCase() === 'object' ) {
  10373. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10374. return;
  10375. }
  10376. if ( type.toLowerCase() === 'scene' ) {
  10377. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10378. return;
  10379. }
  10380. }
  10381. }
  10382. var object = scope.parse( json, texturePath );
  10383. onLoad( object.geometry, object.materials );
  10384. } );
  10385. },
  10386. setCrossOrigin: function ( value ) {
  10387. this.crossOrigin = value;
  10388. },
  10389. setTexturePath: function ( value ) {
  10390. this.texturePath = value;
  10391. },
  10392. parse: function ( json, texturePath ) {
  10393. var geometry = new THREE.Geometry(),
  10394. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10395. parseModel( scale );
  10396. parseSkin();
  10397. parseMorphing( scale );
  10398. parseAnimations();
  10399. geometry.computeFaceNormals();
  10400. geometry.computeBoundingSphere();
  10401. function parseModel( scale ) {
  10402. function isBitSet( value, position ) {
  10403. return value & ( 1 << position );
  10404. }
  10405. var i, j, fi,
  10406. offset, zLength,
  10407. colorIndex, normalIndex, uvIndex, materialIndex,
  10408. type,
  10409. isQuad,
  10410. hasMaterial,
  10411. hasFaceVertexUv,
  10412. hasFaceNormal, hasFaceVertexNormal,
  10413. hasFaceColor, hasFaceVertexColor,
  10414. vertex, face, faceA, faceB, hex, normal,
  10415. uvLayer, uv, u, v,
  10416. faces = json.faces,
  10417. vertices = json.vertices,
  10418. normals = json.normals,
  10419. colors = json.colors,
  10420. nUvLayers = 0;
  10421. if ( json.uvs !== undefined ) {
  10422. // disregard empty arrays
  10423. for ( i = 0; i < json.uvs.length; i ++ ) {
  10424. if ( json.uvs[ i ].length ) nUvLayers ++;
  10425. }
  10426. for ( i = 0; i < nUvLayers; i ++ ) {
  10427. geometry.faceVertexUvs[ i ] = [];
  10428. }
  10429. }
  10430. offset = 0;
  10431. zLength = vertices.length;
  10432. while ( offset < zLength ) {
  10433. vertex = new THREE.Vector3();
  10434. vertex.x = vertices[ offset ++ ] * scale;
  10435. vertex.y = vertices[ offset ++ ] * scale;
  10436. vertex.z = vertices[ offset ++ ] * scale;
  10437. geometry.vertices.push( vertex );
  10438. }
  10439. offset = 0;
  10440. zLength = faces.length;
  10441. while ( offset < zLength ) {
  10442. type = faces[ offset ++ ];
  10443. isQuad = isBitSet( type, 0 );
  10444. hasMaterial = isBitSet( type, 1 );
  10445. hasFaceVertexUv = isBitSet( type, 3 );
  10446. hasFaceNormal = isBitSet( type, 4 );
  10447. hasFaceVertexNormal = isBitSet( type, 5 );
  10448. hasFaceColor = isBitSet( type, 6 );
  10449. hasFaceVertexColor = isBitSet( type, 7 );
  10450. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10451. if ( isQuad ) {
  10452. faceA = new THREE.Face3();
  10453. faceA.a = faces[ offset ];
  10454. faceA.b = faces[ offset + 1 ];
  10455. faceA.c = faces[ offset + 3 ];
  10456. faceB = new THREE.Face3();
  10457. faceB.a = faces[ offset + 1 ];
  10458. faceB.b = faces[ offset + 2 ];
  10459. faceB.c = faces[ offset + 3 ];
  10460. offset += 4;
  10461. if ( hasMaterial ) {
  10462. materialIndex = faces[ offset ++ ];
  10463. faceA.materialIndex = materialIndex;
  10464. faceB.materialIndex = materialIndex;
  10465. }
  10466. // to get face <=> uv index correspondence
  10467. fi = geometry.faces.length;
  10468. if ( hasFaceVertexUv ) {
  10469. for ( i = 0; i < nUvLayers; i ++ ) {
  10470. uvLayer = json.uvs[ i ];
  10471. geometry.faceVertexUvs[ i ][ fi ] = [];
  10472. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10473. for ( j = 0; j < 4; j ++ ) {
  10474. uvIndex = faces[ offset ++ ];
  10475. u = uvLayer[ uvIndex * 2 ];
  10476. v = uvLayer[ uvIndex * 2 + 1 ];
  10477. uv = new THREE.Vector2( u, v );
  10478. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10479. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10480. }
  10481. }
  10482. }
  10483. if ( hasFaceNormal ) {
  10484. normalIndex = faces[ offset ++ ] * 3;
  10485. faceA.normal.set(
  10486. normals[ normalIndex ++ ],
  10487. normals[ normalIndex ++ ],
  10488. normals[ normalIndex ]
  10489. );
  10490. faceB.normal.copy( faceA.normal );
  10491. }
  10492. if ( hasFaceVertexNormal ) {
  10493. for ( i = 0; i < 4; i ++ ) {
  10494. normalIndex = faces[ offset ++ ] * 3;
  10495. normal = new THREE.Vector3(
  10496. normals[ normalIndex ++ ],
  10497. normals[ normalIndex ++ ],
  10498. normals[ normalIndex ]
  10499. );
  10500. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10501. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10502. }
  10503. }
  10504. if ( hasFaceColor ) {
  10505. colorIndex = faces[ offset ++ ];
  10506. hex = colors[ colorIndex ];
  10507. faceA.color.setHex( hex );
  10508. faceB.color.setHex( hex );
  10509. }
  10510. if ( hasFaceVertexColor ) {
  10511. for ( i = 0; i < 4; i ++ ) {
  10512. colorIndex = faces[ offset ++ ];
  10513. hex = colors[ colorIndex ];
  10514. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10515. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10516. }
  10517. }
  10518. geometry.faces.push( faceA );
  10519. geometry.faces.push( faceB );
  10520. } else {
  10521. face = new THREE.Face3();
  10522. face.a = faces[ offset ++ ];
  10523. face.b = faces[ offset ++ ];
  10524. face.c = faces[ offset ++ ];
  10525. if ( hasMaterial ) {
  10526. materialIndex = faces[ offset ++ ];
  10527. face.materialIndex = materialIndex;
  10528. }
  10529. // to get face <=> uv index correspondence
  10530. fi = geometry.faces.length;
  10531. if ( hasFaceVertexUv ) {
  10532. for ( i = 0; i < nUvLayers; i ++ ) {
  10533. uvLayer = json.uvs[ i ];
  10534. geometry.faceVertexUvs[ i ][ fi ] = [];
  10535. for ( j = 0; j < 3; j ++ ) {
  10536. uvIndex = faces[ offset ++ ];
  10537. u = uvLayer[ uvIndex * 2 ];
  10538. v = uvLayer[ uvIndex * 2 + 1 ];
  10539. uv = new THREE.Vector2( u, v );
  10540. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10541. }
  10542. }
  10543. }
  10544. if ( hasFaceNormal ) {
  10545. normalIndex = faces[ offset ++ ] * 3;
  10546. face.normal.set(
  10547. normals[ normalIndex ++ ],
  10548. normals[ normalIndex ++ ],
  10549. normals[ normalIndex ]
  10550. );
  10551. }
  10552. if ( hasFaceVertexNormal ) {
  10553. for ( i = 0; i < 3; i ++ ) {
  10554. normalIndex = faces[ offset ++ ] * 3;
  10555. normal = new THREE.Vector3(
  10556. normals[ normalIndex ++ ],
  10557. normals[ normalIndex ++ ],
  10558. normals[ normalIndex ]
  10559. );
  10560. face.vertexNormals.push( normal );
  10561. }
  10562. }
  10563. if ( hasFaceColor ) {
  10564. colorIndex = faces[ offset ++ ];
  10565. face.color.setHex( colors[ colorIndex ] );
  10566. }
  10567. if ( hasFaceVertexColor ) {
  10568. for ( i = 0; i < 3; i ++ ) {
  10569. colorIndex = faces[ offset ++ ];
  10570. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  10571. }
  10572. }
  10573. geometry.faces.push( face );
  10574. }
  10575. }
  10576. };
  10577. function parseSkin() {
  10578. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  10579. if ( json.skinWeights ) {
  10580. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  10581. var x = json.skinWeights[ i ];
  10582. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  10583. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  10584. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  10585. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10586. }
  10587. }
  10588. if ( json.skinIndices ) {
  10589. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  10590. var a = json.skinIndices[ i ];
  10591. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  10592. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  10593. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  10594. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10595. }
  10596. }
  10597. geometry.bones = json.bones;
  10598. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  10599. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  10600. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  10601. }
  10602. };
  10603. function parseMorphing( scale ) {
  10604. if ( json.morphTargets !== undefined ) {
  10605. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10606. geometry.morphTargets[ i ] = {};
  10607. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10608. geometry.morphTargets[ i ].vertices = [];
  10609. var dstVertices = geometry.morphTargets[ i ].vertices;
  10610. var srcVertices = json.morphTargets[ i ].vertices;
  10611. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10612. var vertex = new THREE.Vector3();
  10613. vertex.x = srcVertices[ v ] * scale;
  10614. vertex.y = srcVertices[ v + 1 ] * scale;
  10615. vertex.z = srcVertices[ v + 2 ] * scale;
  10616. dstVertices.push( vertex );
  10617. }
  10618. }
  10619. }
  10620. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  10621. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  10622. var faces = geometry.faces;
  10623. var morphColors = json.morphColors[ 0 ].colors;
  10624. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  10625. faces[ i ].color.fromArray( morphColors, i * 3 );
  10626. }
  10627. }
  10628. }
  10629. function parseAnimations() {
  10630. var outputAnimations = [];
  10631. // parse old style Bone/Hierarchy animations
  10632. var animations = [];
  10633. if ( json.animation !== undefined ) {
  10634. animations.push( json.animation );
  10635. }
  10636. if ( json.animations !== undefined ) {
  10637. if ( json.animations.length ) {
  10638. animations = animations.concat( json.animations );
  10639. } else {
  10640. animations.push( json.animations );
  10641. }
  10642. }
  10643. for ( var i = 0; i < animations.length; i ++ ) {
  10644. var clip = THREE.AnimationClip.parseAnimation( animations[i], geometry.bones );
  10645. if ( clip ) outputAnimations.push( clip );
  10646. }
  10647. // parse implicit morph animations
  10648. if ( geometry.morphTargets ) {
  10649. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  10650. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  10651. outputAnimations = outputAnimations.concat( morphAnimationClips );
  10652. }
  10653. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  10654. };
  10655. if ( json.materials === undefined || json.materials.length === 0 ) {
  10656. return { geometry: geometry };
  10657. } else {
  10658. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  10659. return { geometry: geometry, materials: materials };
  10660. }
  10661. }
  10662. };
  10663. // File:src/loaders/LoadingManager.js
  10664. /**
  10665. * @author mrdoob / http://mrdoob.com/
  10666. */
  10667. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  10668. var scope = this;
  10669. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  10670. this.onStart = undefined;
  10671. this.onLoad = onLoad;
  10672. this.onProgress = onProgress;
  10673. this.onError = onError;
  10674. this.itemStart = function ( url ) {
  10675. itemsTotal ++;
  10676. if ( isLoading === false ) {
  10677. if ( scope.onStart !== undefined ) {
  10678. scope.onStart( url, itemsLoaded, itemsTotal );
  10679. }
  10680. }
  10681. isLoading = true;
  10682. };
  10683. this.itemEnd = function ( url ) {
  10684. itemsLoaded ++;
  10685. if ( scope.onProgress !== undefined ) {
  10686. scope.onProgress( url, itemsLoaded, itemsTotal );
  10687. }
  10688. if ( itemsLoaded === itemsTotal ) {
  10689. isLoading = false;
  10690. if ( scope.onLoad !== undefined ) {
  10691. scope.onLoad();
  10692. }
  10693. }
  10694. };
  10695. this.itemError = function ( url ) {
  10696. if ( scope.onError !== undefined ) {
  10697. scope.onError( url );
  10698. }
  10699. };
  10700. };
  10701. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  10702. // File:src/loaders/BufferGeometryLoader.js
  10703. /**
  10704. * @author mrdoob / http://mrdoob.com/
  10705. */
  10706. THREE.BufferGeometryLoader = function ( manager ) {
  10707. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10708. };
  10709. THREE.BufferGeometryLoader.prototype = {
  10710. constructor: THREE.BufferGeometryLoader,
  10711. load: function ( url, onLoad, onProgress, onError ) {
  10712. var scope = this;
  10713. var loader = new THREE.XHRLoader( scope.manager );
  10714. loader.setCrossOrigin( this.crossOrigin );
  10715. loader.load( url, function ( text ) {
  10716. onLoad( scope.parse( JSON.parse( text ) ) );
  10717. }, onProgress, onError );
  10718. },
  10719. setCrossOrigin: function ( value ) {
  10720. this.crossOrigin = value;
  10721. },
  10722. parse: function ( json ) {
  10723. var geometry = new THREE.BufferGeometry();
  10724. var index = json.data.index;
  10725. if ( index !== undefined ) {
  10726. var typedArray = new self[ index.type ]( index.array );
  10727. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  10728. }
  10729. var attributes = json.data.attributes;
  10730. for ( var key in attributes ) {
  10731. var attribute = attributes[ key ];
  10732. var typedArray = new self[ attribute.type ]( attribute.array );
  10733. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  10734. }
  10735. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  10736. if ( groups !== undefined ) {
  10737. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  10738. var group = groups[ i ];
  10739. geometry.addGroup( group.start, group.count, group.materialIndex );
  10740. }
  10741. }
  10742. var boundingSphere = json.data.boundingSphere;
  10743. if ( boundingSphere !== undefined ) {
  10744. var center = new THREE.Vector3();
  10745. if ( boundingSphere.center !== undefined ) {
  10746. center.fromArray( boundingSphere.center );
  10747. }
  10748. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  10749. }
  10750. return geometry;
  10751. }
  10752. };
  10753. // File:src/loaders/MaterialLoader.js
  10754. /**
  10755. * @author mrdoob / http://mrdoob.com/
  10756. */
  10757. THREE.MaterialLoader = function ( manager ) {
  10758. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10759. this.textures = {};
  10760. };
  10761. THREE.MaterialLoader.prototype = {
  10762. constructor: THREE.MaterialLoader,
  10763. load: function ( url, onLoad, onProgress, onError ) {
  10764. var scope = this;
  10765. var loader = new THREE.XHRLoader( scope.manager );
  10766. loader.setCrossOrigin( this.crossOrigin );
  10767. loader.load( url, function ( text ) {
  10768. onLoad( scope.parse( JSON.parse( text ) ) );
  10769. }, onProgress, onError );
  10770. },
  10771. setCrossOrigin: function ( value ) {
  10772. this.crossOrigin = value;
  10773. },
  10774. setTextures: function ( value ) {
  10775. this.textures = value;
  10776. },
  10777. getTexture: function ( name ) {
  10778. var textures = this.textures;
  10779. if ( textures[ name ] === undefined ) {
  10780. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  10781. }
  10782. return textures[ name ];
  10783. },
  10784. parse: function ( json ) {
  10785. var material = new THREE[ json.type ];
  10786. material.uuid = json.uuid;
  10787. if ( json.name !== undefined ) material.name = json.name;
  10788. if ( json.color !== undefined ) material.color.setHex( json.color );
  10789. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  10790. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  10791. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  10792. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  10793. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  10794. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  10795. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  10796. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  10797. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  10798. if ( json.shading !== undefined ) material.shading = json.shading;
  10799. if ( json.blending !== undefined ) material.blending = json.blending;
  10800. if ( json.side !== undefined ) material.side = json.side;
  10801. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  10802. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  10803. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  10804. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  10805. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  10806. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  10807. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  10808. // for PointsMaterial
  10809. if ( json.size !== undefined ) material.size = json.size;
  10810. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  10811. // maps
  10812. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  10813. if ( json.alphaMap !== undefined ) {
  10814. material.alphaMap = this.getTexture( json.alphaMap );
  10815. material.transparent = true;
  10816. }
  10817. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  10818. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  10819. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  10820. if ( json.normalScale !== undefined ) {
  10821. var normalScale = json.normalScale;
  10822. if ( Array.isArray( normalScale ) === false ) {
  10823. // Blender exporter used to export a scalar. See #7459
  10824. normalScale = [ normalScale, normalScale ];
  10825. }
  10826. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  10827. }
  10828. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  10829. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  10830. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  10831. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  10832. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  10833. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  10834. if ( json.envMap !== undefined ) {
  10835. material.envMap = this.getTexture( json.envMap );
  10836. material.combine = THREE.MultiplyOperation;
  10837. }
  10838. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  10839. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  10840. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  10841. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  10842. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  10843. // MeshFaceMaterial
  10844. if ( json.materials !== undefined ) {
  10845. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  10846. material.materials.push( this.parse( json.materials[ i ] ) );
  10847. }
  10848. }
  10849. return material;
  10850. }
  10851. };
  10852. // File:src/loaders/ObjectLoader.js
  10853. /**
  10854. * @author mrdoob / http://mrdoob.com/
  10855. */
  10856. THREE.ObjectLoader = function ( manager ) {
  10857. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10858. this.texturePath = '';
  10859. };
  10860. THREE.ObjectLoader.prototype = {
  10861. constructor: THREE.ObjectLoader,
  10862. load: function ( url, onLoad, onProgress, onError ) {
  10863. if ( this.texturePath === '' ) {
  10864. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  10865. }
  10866. var scope = this;
  10867. var loader = new THREE.XHRLoader( scope.manager );
  10868. loader.setCrossOrigin( this.crossOrigin );
  10869. loader.load( url, function ( text ) {
  10870. scope.parse( JSON.parse( text ), onLoad );
  10871. }, onProgress, onError );
  10872. },
  10873. setTexturePath: function ( value ) {
  10874. this.texturePath = value;
  10875. },
  10876. setCrossOrigin: function ( value ) {
  10877. this.crossOrigin = value;
  10878. },
  10879. parse: function ( json, onLoad ) {
  10880. var geometries = this.parseGeometries( json.geometries );
  10881. var images = this.parseImages( json.images, function () {
  10882. if ( onLoad !== undefined ) onLoad( object );
  10883. } );
  10884. var textures = this.parseTextures( json.textures, images );
  10885. var materials = this.parseMaterials( json.materials, textures );
  10886. var object = this.parseObject( json.object, geometries, materials );
  10887. if ( json.animations ) {
  10888. object.animations = this.parseAnimations( json.animations );
  10889. }
  10890. if ( json.images === undefined || json.images.length === 0 ) {
  10891. if ( onLoad !== undefined ) onLoad( object );
  10892. }
  10893. return object;
  10894. },
  10895. parseGeometries: function ( json ) {
  10896. var geometries = {};
  10897. if ( json !== undefined ) {
  10898. var geometryLoader = new THREE.JSONLoader();
  10899. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  10900. for ( var i = 0, l = json.length; i < l; i ++ ) {
  10901. var geometry;
  10902. var data = json[ i ];
  10903. switch ( data.type ) {
  10904. case 'PlaneGeometry':
  10905. case 'PlaneBufferGeometry':
  10906. geometry = new THREE[ data.type ](
  10907. data.width,
  10908. data.height,
  10909. data.widthSegments,
  10910. data.heightSegments
  10911. );
  10912. break;
  10913. case 'BoxGeometry':
  10914. case 'CubeGeometry': // backwards compatible
  10915. geometry = new THREE.BoxGeometry(
  10916. data.width,
  10917. data.height,
  10918. data.depth,
  10919. data.widthSegments,
  10920. data.heightSegments,
  10921. data.depthSegments
  10922. );
  10923. break;
  10924. case 'CircleBufferGeometry':
  10925. geometry = new THREE.CircleBufferGeometry(
  10926. data.radius,
  10927. data.segments,
  10928. data.thetaStart,
  10929. data.thetaLength
  10930. );
  10931. break;
  10932. case 'CircleGeometry':
  10933. geometry = new THREE.CircleGeometry(
  10934. data.radius,
  10935. data.segments,
  10936. data.thetaStart,
  10937. data.thetaLength
  10938. );
  10939. break;
  10940. case 'CylinderGeometry':
  10941. geometry = new THREE.CylinderGeometry(
  10942. data.radiusTop,
  10943. data.radiusBottom,
  10944. data.height,
  10945. data.radialSegments,
  10946. data.heightSegments,
  10947. data.openEnded,
  10948. data.thetaStart,
  10949. data.thetaLength
  10950. );
  10951. break;
  10952. case 'SphereGeometry':
  10953. geometry = new THREE.SphereGeometry(
  10954. data.radius,
  10955. data.widthSegments,
  10956. data.heightSegments,
  10957. data.phiStart,
  10958. data.phiLength,
  10959. data.thetaStart,
  10960. data.thetaLength
  10961. );
  10962. break;
  10963. case 'SphereBufferGeometry':
  10964. geometry = new THREE.SphereBufferGeometry(
  10965. data.radius,
  10966. data.widthSegments,
  10967. data.heightSegments,
  10968. data.phiStart,
  10969. data.phiLength,
  10970. data.thetaStart,
  10971. data.thetaLength
  10972. );
  10973. break;
  10974. case 'DodecahedronGeometry':
  10975. geometry = new THREE.DodecahedronGeometry(
  10976. data.radius,
  10977. data.detail
  10978. );
  10979. break;
  10980. case 'IcosahedronGeometry':
  10981. geometry = new THREE.IcosahedronGeometry(
  10982. data.radius,
  10983. data.detail
  10984. );
  10985. break;
  10986. case 'OctahedronGeometry':
  10987. geometry = new THREE.OctahedronGeometry(
  10988. data.radius,
  10989. data.detail
  10990. );
  10991. break;
  10992. case 'TetrahedronGeometry':
  10993. geometry = new THREE.TetrahedronGeometry(
  10994. data.radius,
  10995. data.detail
  10996. );
  10997. break;
  10998. case 'RingGeometry':
  10999. geometry = new THREE.RingGeometry(
  11000. data.innerRadius,
  11001. data.outerRadius,
  11002. data.thetaSegments,
  11003. data.phiSegments,
  11004. data.thetaStart,
  11005. data.thetaLength
  11006. );
  11007. break;
  11008. case 'TorusGeometry':
  11009. geometry = new THREE.TorusGeometry(
  11010. data.radius,
  11011. data.tube,
  11012. data.radialSegments,
  11013. data.tubularSegments,
  11014. data.arc
  11015. );
  11016. break;
  11017. case 'TorusKnotGeometry':
  11018. geometry = new THREE.TorusKnotGeometry(
  11019. data.radius,
  11020. data.tube,
  11021. data.radialSegments,
  11022. data.tubularSegments,
  11023. data.p,
  11024. data.q,
  11025. data.heightScale
  11026. );
  11027. break;
  11028. case 'BufferGeometry':
  11029. geometry = bufferGeometryLoader.parse( data );
  11030. break;
  11031. case 'Geometry':
  11032. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11033. break;
  11034. default:
  11035. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11036. continue;
  11037. }
  11038. geometry.uuid = data.uuid;
  11039. if ( data.name !== undefined ) geometry.name = data.name;
  11040. geometries[ data.uuid ] = geometry;
  11041. }
  11042. }
  11043. return geometries;
  11044. },
  11045. parseMaterials: function ( json, textures ) {
  11046. var materials = {};
  11047. if ( json !== undefined ) {
  11048. var loader = new THREE.MaterialLoader();
  11049. loader.setTextures( textures );
  11050. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11051. var material = loader.parse( json[ i ] );
  11052. materials[ material.uuid ] = material;
  11053. }
  11054. }
  11055. return materials;
  11056. },
  11057. parseAnimations: function ( json ) {
  11058. var animations = [];
  11059. for ( var i = 0; i < json.length; i ++ ) {
  11060. var clip = THREE.AnimationClip.parse( json[i] );
  11061. animations.push( clip );
  11062. }
  11063. return animations;
  11064. },
  11065. parseImages: function ( json, onLoad ) {
  11066. var scope = this;
  11067. var images = {};
  11068. function loadImage( url ) {
  11069. scope.manager.itemStart( url );
  11070. return loader.load( url, function () {
  11071. scope.manager.itemEnd( url );
  11072. } );
  11073. }
  11074. if ( json !== undefined && json.length > 0 ) {
  11075. var manager = new THREE.LoadingManager( onLoad );
  11076. var loader = new THREE.ImageLoader( manager );
  11077. loader.setCrossOrigin( this.crossOrigin );
  11078. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11079. var image = json[ i ];
  11080. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11081. images[ image.uuid ] = loadImage( path );
  11082. }
  11083. }
  11084. return images;
  11085. },
  11086. parseTextures: function ( json, images ) {
  11087. function parseConstant( value ) {
  11088. if ( typeof( value ) === 'number' ) return value;
  11089. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11090. return THREE[ value ];
  11091. }
  11092. var textures = {};
  11093. if ( json !== undefined ) {
  11094. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11095. var data = json[ i ];
  11096. if ( data.image === undefined ) {
  11097. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11098. }
  11099. if ( images[ data.image ] === undefined ) {
  11100. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11101. }
  11102. var texture = new THREE.Texture( images[ data.image ] );
  11103. texture.needsUpdate = true;
  11104. texture.uuid = data.uuid;
  11105. if ( data.name !== undefined ) texture.name = data.name;
  11106. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11107. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11108. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11109. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11110. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11111. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11112. if ( Array.isArray( data.wrap ) ) {
  11113. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11114. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11115. }
  11116. textures[ data.uuid ] = texture;
  11117. }
  11118. }
  11119. return textures;
  11120. },
  11121. parseObject: function () {
  11122. var matrix = new THREE.Matrix4();
  11123. return function ( data, geometries, materials ) {
  11124. var object;
  11125. function getGeometry( name ) {
  11126. if ( geometries[ name ] === undefined ) {
  11127. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11128. }
  11129. return geometries[ name ];
  11130. }
  11131. function getMaterial( name ) {
  11132. if ( name === undefined ) return undefined;
  11133. if ( materials[ name ] === undefined ) {
  11134. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11135. }
  11136. return materials[ name ];
  11137. }
  11138. switch ( data.type ) {
  11139. case 'Scene':
  11140. object = new THREE.Scene();
  11141. break;
  11142. case 'PerspectiveCamera':
  11143. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  11144. break;
  11145. case 'OrthographicCamera':
  11146. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11147. break;
  11148. case 'AmbientLight':
  11149. object = new THREE.AmbientLight( data.color );
  11150. break;
  11151. case 'DirectionalLight':
  11152. object = new THREE.DirectionalLight( data.color, data.intensity );
  11153. break;
  11154. case 'PointLight':
  11155. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11156. break;
  11157. case 'SpotLight':
  11158. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  11159. break;
  11160. case 'HemisphereLight':
  11161. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11162. break;
  11163. case 'Mesh':
  11164. var geometry = getGeometry( data.geometry );
  11165. var material = getMaterial( data.material );
  11166. if ( geometry.bones && geometry.bones.length > 0 ) {
  11167. object = new THREE.SkinnedMesh( geometry, material );
  11168. } else {
  11169. object = new THREE.Mesh( geometry, material );
  11170. }
  11171. break;
  11172. case 'LOD':
  11173. object = new THREE.LOD();
  11174. break;
  11175. case 'Line':
  11176. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11177. break;
  11178. case 'PointCloud':
  11179. case 'Points':
  11180. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11181. break;
  11182. case 'Sprite':
  11183. object = new THREE.Sprite( getMaterial( data.material ) );
  11184. break;
  11185. case 'Group':
  11186. object = new THREE.Group();
  11187. break;
  11188. default:
  11189. object = new THREE.Object3D();
  11190. }
  11191. object.uuid = data.uuid;
  11192. if ( data.name !== undefined ) object.name = data.name;
  11193. if ( data.matrix !== undefined ) {
  11194. matrix.fromArray( data.matrix );
  11195. matrix.decompose( object.position, object.quaternion, object.scale );
  11196. } else {
  11197. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11198. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11199. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11200. }
  11201. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11202. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11203. if ( data.visible !== undefined ) object.visible = data.visible;
  11204. if ( data.userData !== undefined ) object.userData = data.userData;
  11205. if ( data.children !== undefined ) {
  11206. for ( var child in data.children ) {
  11207. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11208. }
  11209. }
  11210. if ( data.type === 'LOD' ) {
  11211. var levels = data.levels;
  11212. for ( var l = 0; l < levels.length; l ++ ) {
  11213. var level = levels[ l ];
  11214. var child = object.getObjectByProperty( 'uuid', level.object );
  11215. if ( child !== undefined ) {
  11216. object.addLevel( child, level.distance );
  11217. }
  11218. }
  11219. }
  11220. return object;
  11221. }
  11222. }()
  11223. };
  11224. // File:src/loaders/TextureLoader.js
  11225. /**
  11226. * @author mrdoob / http://mrdoob.com/
  11227. */
  11228. THREE.TextureLoader = function ( manager ) {
  11229. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11230. };
  11231. THREE.TextureLoader.prototype = {
  11232. constructor: THREE.TextureLoader,
  11233. load: function ( url, onLoad, onProgress, onError ) {
  11234. var texture = new THREE.Texture();
  11235. var loader = new THREE.ImageLoader( this.manager );
  11236. loader.setCrossOrigin( this.crossOrigin );
  11237. loader.setPath( this.path );
  11238. loader.load( url, function ( image ) {
  11239. texture.image = image;
  11240. texture.needsUpdate = true;
  11241. if ( onLoad !== undefined ) {
  11242. onLoad( texture );
  11243. }
  11244. }, onProgress, onError );
  11245. return texture;
  11246. },
  11247. setCrossOrigin: function ( value ) {
  11248. this.crossOrigin = value;
  11249. },
  11250. setPath: function ( value ) {
  11251. this.path = value;
  11252. }
  11253. };
  11254. // File:src/loaders/CubeTextureLoader.js
  11255. /**
  11256. * @author mrdoob / http://mrdoob.com/
  11257. */
  11258. THREE.CubeTextureLoader = function ( manager ) {
  11259. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11260. };
  11261. THREE.CubeTextureLoader.prototype = {
  11262. constructor: THREE.CubeTextureLoader,
  11263. load: function ( urls, onLoad, onProgress, onError ) {
  11264. var texture = new THREE.CubeTexture( [] );
  11265. var loader = new THREE.ImageLoader();
  11266. loader.setCrossOrigin( this.crossOrigin );
  11267. loader.setPath( this.path );
  11268. var loaded = 0;
  11269. function loadTexture( i ) {
  11270. loader.load( urls[ i ], function ( image ) {
  11271. texture.images[ i ] = image;
  11272. loaded ++;
  11273. if ( loaded === 6 ) {
  11274. texture.needsUpdate = true;
  11275. if ( onLoad ) onLoad( texture );
  11276. }
  11277. }, undefined, onError );
  11278. }
  11279. for ( var i = 0; i < urls.length; ++ i ) {
  11280. loadTexture( i );
  11281. }
  11282. return texture;
  11283. },
  11284. setCrossOrigin: function ( value ) {
  11285. this.crossOrigin = value;
  11286. },
  11287. setPath: function ( value ) {
  11288. this.path = value;
  11289. }
  11290. };
  11291. // File:src/loaders/BinaryTextureLoader.js
  11292. /**
  11293. * @author Nikos M. / https://github.com/foo123/
  11294. *
  11295. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11296. */
  11297. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11298. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11299. // override in sub classes
  11300. this._parser = null;
  11301. };
  11302. THREE.BinaryTextureLoader.prototype = {
  11303. constructor: THREE.BinaryTextureLoader,
  11304. load: function ( url, onLoad, onProgress, onError ) {
  11305. var scope = this;
  11306. var texture = new THREE.DataTexture();
  11307. var loader = new THREE.XHRLoader( this.manager );
  11308. loader.setCrossOrigin( this.crossOrigin );
  11309. loader.setResponseType( 'arraybuffer' );
  11310. loader.load( url, function ( buffer ) {
  11311. var texData = scope._parser( buffer );
  11312. if ( ! texData ) return;
  11313. if ( undefined !== texData.image ) {
  11314. texture.image = texData.image;
  11315. } else if ( undefined !== texData.data ) {
  11316. texture.image.width = texData.width;
  11317. texture.image.height = texData.height;
  11318. texture.image.data = texData.data;
  11319. }
  11320. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11321. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11322. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11323. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11324. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11325. if ( undefined !== texData.format ) {
  11326. texture.format = texData.format;
  11327. }
  11328. if ( undefined !== texData.type ) {
  11329. texture.type = texData.type;
  11330. }
  11331. if ( undefined !== texData.mipmaps ) {
  11332. texture.mipmaps = texData.mipmaps;
  11333. }
  11334. if ( 1 === texData.mipmapCount ) {
  11335. texture.minFilter = THREE.LinearFilter;
  11336. }
  11337. texture.needsUpdate = true;
  11338. if ( onLoad ) onLoad( texture, texData );
  11339. }, onProgress, onError );
  11340. return texture;
  11341. },
  11342. setCrossOrigin: function ( value ) {
  11343. this.crossOrigin = value;
  11344. }
  11345. };
  11346. // File:src/loaders/CompressedTextureLoader.js
  11347. /**
  11348. * @author mrdoob / http://mrdoob.com/
  11349. *
  11350. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11351. */
  11352. THREE.CompressedTextureLoader = function ( manager ) {
  11353. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11354. // override in sub classes
  11355. this._parser = null;
  11356. };
  11357. THREE.CompressedTextureLoader.prototype = {
  11358. constructor: THREE.CompressedTextureLoader,
  11359. load: function ( url, onLoad, onProgress, onError ) {
  11360. var scope = this;
  11361. var images = [];
  11362. var texture = new THREE.CompressedTexture();
  11363. texture.image = images;
  11364. var loader = new THREE.XHRLoader( this.manager );
  11365. loader.setCrossOrigin( this.crossOrigin );
  11366. loader.setPath( this.path );
  11367. loader.setResponseType( 'arraybuffer' );
  11368. function loadTexture( i ) {
  11369. loader.load( url[ i ], function ( buffer ) {
  11370. var texDatas = scope._parser( buffer, true );
  11371. images[ i ] = {
  11372. width: texDatas.width,
  11373. height: texDatas.height,
  11374. format: texDatas.format,
  11375. mipmaps: texDatas.mipmaps
  11376. };
  11377. loaded += 1;
  11378. if ( loaded === 6 ) {
  11379. if ( texDatas.mipmapCount === 1 )
  11380. texture.minFilter = THREE.LinearFilter;
  11381. texture.format = texDatas.format;
  11382. texture.needsUpdate = true;
  11383. if ( onLoad ) onLoad( texture );
  11384. }
  11385. }, onProgress, onError );
  11386. }
  11387. if ( Array.isArray( url ) ) {
  11388. var loaded = 0;
  11389. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11390. loadTexture( i );
  11391. }
  11392. } else {
  11393. // compressed cubemap texture stored in a single DDS file
  11394. loader.load( url, function ( buffer ) {
  11395. var texDatas = scope._parser( buffer, true );
  11396. if ( texDatas.isCubemap ) {
  11397. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11398. for ( var f = 0; f < faces; f ++ ) {
  11399. images[ f ] = { mipmaps : [] };
  11400. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11401. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11402. images[ f ].format = texDatas.format;
  11403. images[ f ].width = texDatas.width;
  11404. images[ f ].height = texDatas.height;
  11405. }
  11406. }
  11407. } else {
  11408. texture.image.width = texDatas.width;
  11409. texture.image.height = texDatas.height;
  11410. texture.mipmaps = texDatas.mipmaps;
  11411. }
  11412. if ( texDatas.mipmapCount === 1 ) {
  11413. texture.minFilter = THREE.LinearFilter;
  11414. }
  11415. texture.format = texDatas.format;
  11416. texture.needsUpdate = true;
  11417. if ( onLoad ) onLoad( texture );
  11418. }, onProgress, onError );
  11419. }
  11420. return texture;
  11421. },
  11422. setCrossOrigin: function ( value ) {
  11423. this.crossOrigin = value;
  11424. },
  11425. setPath: function ( value ) {
  11426. this.path = value;
  11427. }
  11428. };
  11429. // File:src/materials/Material.js
  11430. /**
  11431. * @author mrdoob / http://mrdoob.com/
  11432. * @author alteredq / http://alteredqualia.com/
  11433. */
  11434. THREE.Material = function () {
  11435. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11436. this.uuid = THREE.Math.generateUUID();
  11437. this.name = '';
  11438. this.type = 'Material';
  11439. this.side = THREE.FrontSide;
  11440. this.opacity = 1;
  11441. this.transparent = false;
  11442. this.blending = THREE.NormalBlending;
  11443. this.blendSrc = THREE.SrcAlphaFactor;
  11444. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11445. this.blendEquation = THREE.AddEquation;
  11446. this.blendSrcAlpha = null;
  11447. this.blendDstAlpha = null;
  11448. this.blendEquationAlpha = null;
  11449. this.depthFunc = THREE.LessEqualDepth;
  11450. this.depthTest = true;
  11451. this.depthWrite = true;
  11452. this.colorWrite = true;
  11453. this.precision = null; // override the renderer's default precision for this material
  11454. this.polygonOffset = false;
  11455. this.polygonOffsetFactor = 0;
  11456. this.polygonOffsetUnits = 0;
  11457. this.alphaTest = 0;
  11458. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11459. this.visible = true;
  11460. this._needsUpdate = true;
  11461. };
  11462. THREE.Material.prototype = {
  11463. constructor: THREE.Material,
  11464. get needsUpdate () {
  11465. return this._needsUpdate;
  11466. },
  11467. set needsUpdate ( value ) {
  11468. if ( value === true ) this.update();
  11469. this._needsUpdate = value;
  11470. },
  11471. setValues: function ( values ) {
  11472. if ( values === undefined ) return;
  11473. for ( var key in values ) {
  11474. var newValue = values[ key ];
  11475. if ( newValue === undefined ) {
  11476. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11477. continue;
  11478. }
  11479. var currentValue = this[ key ];
  11480. if ( currentValue === undefined ) {
  11481. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11482. continue;
  11483. }
  11484. if ( currentValue instanceof THREE.Color ) {
  11485. currentValue.set( newValue );
  11486. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11487. currentValue.copy( newValue );
  11488. } else if ( key === 'overdraw' ) {
  11489. // ensure overdraw is backwards-compatible with legacy boolean type
  11490. this[ key ] = Number( newValue );
  11491. } else {
  11492. this[ key ] = newValue;
  11493. }
  11494. }
  11495. },
  11496. toJSON: function ( meta ) {
  11497. var isRoot = meta === undefined;
  11498. if ( isRoot ) {
  11499. meta = {
  11500. textures: {},
  11501. images: {}
  11502. };
  11503. }
  11504. var data = {
  11505. metadata: {
  11506. version: 4.4,
  11507. type: 'Material',
  11508. generator: 'Material.toJSON'
  11509. }
  11510. };
  11511. // standard Material serialization
  11512. data.uuid = this.uuid;
  11513. data.type = this.type;
  11514. if ( this.name !== '' ) data.name = this.name;
  11515. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11516. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11517. if ( this.metalness > 0 ) data.metalness = this.metalness;
  11518. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11519. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11520. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11521. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11522. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11523. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11524. if ( this.bumpMap instanceof THREE.Texture ) {
  11525. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11526. data.bumpScale = this.bumpScale;
  11527. }
  11528. if ( this.normalMap instanceof THREE.Texture ) {
  11529. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11530. data.normalScale = this.normalScale.toArray();
  11531. }
  11532. if ( this.displacementMap instanceof THREE.Texture ) {
  11533. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11534. data.displacementScale = this.displacementScale;
  11535. data.displacementBias = this.displacementBias;
  11536. }
  11537. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11538. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11539. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11540. if ( this.envMap instanceof THREE.Texture ) {
  11541. data.envMap = this.envMap.toJSON( meta ).uuid;
  11542. data.reflectivity = this.reflectivity; // Scale behind envMap
  11543. }
  11544. if ( this.size !== undefined ) data.size = this.size;
  11545. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11546. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  11547. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  11548. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  11549. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  11550. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11551. if ( this.transparent === true ) data.transparent = this.transparent;
  11552. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11553. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11554. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11555. // TODO: Copied from Object3D.toJSON
  11556. function extractFromCache ( cache ) {
  11557. var values = [];
  11558. for ( var key in cache ) {
  11559. var data = cache[ key ];
  11560. delete data.metadata;
  11561. values.push( data );
  11562. }
  11563. return values;
  11564. }
  11565. if ( isRoot ) {
  11566. var textures = extractFromCache( meta.textures );
  11567. var images = extractFromCache( meta.images );
  11568. if ( textures.length > 0 ) data.textures = textures;
  11569. if ( images.length > 0 ) data.images = images;
  11570. }
  11571. return data;
  11572. },
  11573. clone: function () {
  11574. return new this.constructor().copy( this );
  11575. },
  11576. copy: function ( source ) {
  11577. this.name = source.name;
  11578. this.side = source.side;
  11579. this.opacity = source.opacity;
  11580. this.transparent = source.transparent;
  11581. this.blending = source.blending;
  11582. this.blendSrc = source.blendSrc;
  11583. this.blendDst = source.blendDst;
  11584. this.blendEquation = source.blendEquation;
  11585. this.blendSrcAlpha = source.blendSrcAlpha;
  11586. this.blendDstAlpha = source.blendDstAlpha;
  11587. this.blendEquationAlpha = source.blendEquationAlpha;
  11588. this.depthFunc = source.depthFunc;
  11589. this.depthTest = source.depthTest;
  11590. this.depthWrite = source.depthWrite;
  11591. this.precision = source.precision;
  11592. this.polygonOffset = source.polygonOffset;
  11593. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11594. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11595. this.alphaTest = source.alphaTest;
  11596. this.overdraw = source.overdraw;
  11597. this.visible = source.visible;
  11598. return this;
  11599. },
  11600. update: function () {
  11601. this.dispatchEvent( { type: 'update' } );
  11602. },
  11603. dispose: function () {
  11604. this.dispatchEvent( { type: 'dispose' } );
  11605. }
  11606. };
  11607. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  11608. THREE.MaterialIdCount = 0;
  11609. // File:src/materials/LineBasicMaterial.js
  11610. /**
  11611. * @author mrdoob / http://mrdoob.com/
  11612. * @author alteredq / http://alteredqualia.com/
  11613. *
  11614. * parameters = {
  11615. * color: <hex>,
  11616. * opacity: <float>,
  11617. *
  11618. * blending: THREE.NormalBlending,
  11619. * depthTest: <bool>,
  11620. * depthWrite: <bool>,
  11621. *
  11622. * linewidth: <float>,
  11623. * linecap: "round",
  11624. * linejoin: "round",
  11625. *
  11626. * vertexColors: <bool>
  11627. *
  11628. * fog: <bool>
  11629. * }
  11630. */
  11631. THREE.LineBasicMaterial = function ( parameters ) {
  11632. THREE.Material.call( this );
  11633. this.type = 'LineBasicMaterial';
  11634. this.color = new THREE.Color( 0xffffff );
  11635. this.linewidth = 1;
  11636. this.linecap = 'round';
  11637. this.linejoin = 'round';
  11638. this.vertexColors = THREE.NoColors;
  11639. this.fog = true;
  11640. this.setValues( parameters );
  11641. };
  11642. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11643. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  11644. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  11645. THREE.Material.prototype.copy.call( this, source );
  11646. this.color.copy( source.color );
  11647. this.linewidth = source.linewidth;
  11648. this.linecap = source.linecap;
  11649. this.linejoin = source.linejoin;
  11650. this.vertexColors = source.vertexColors;
  11651. this.fog = source.fog;
  11652. return this;
  11653. };
  11654. // File:src/materials/LineDashedMaterial.js
  11655. /**
  11656. * @author alteredq / http://alteredqualia.com/
  11657. *
  11658. * parameters = {
  11659. * color: <hex>,
  11660. * opacity: <float>,
  11661. *
  11662. * blending: THREE.NormalBlending,
  11663. * depthTest: <bool>,
  11664. * depthWrite: <bool>,
  11665. *
  11666. * linewidth: <float>,
  11667. *
  11668. * scale: <float>,
  11669. * dashSize: <float>,
  11670. * gapSize: <float>,
  11671. *
  11672. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  11673. *
  11674. * fog: <bool>
  11675. * }
  11676. */
  11677. THREE.LineDashedMaterial = function ( parameters ) {
  11678. THREE.Material.call( this );
  11679. this.type = 'LineDashedMaterial';
  11680. this.color = new THREE.Color( 0xffffff );
  11681. this.linewidth = 1;
  11682. this.scale = 1;
  11683. this.dashSize = 3;
  11684. this.gapSize = 1;
  11685. this.vertexColors = THREE.NoColors;
  11686. this.fog = true;
  11687. this.setValues( parameters );
  11688. };
  11689. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  11690. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  11691. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  11692. THREE.Material.prototype.copy.call( this, source );
  11693. this.color.copy( source.color );
  11694. this.linewidth = source.linewidth;
  11695. this.scale = source.scale;
  11696. this.dashSize = source.dashSize;
  11697. this.gapSize = source.gapSize;
  11698. this.vertexColors = source.vertexColors;
  11699. this.fog = source.fog;
  11700. return this;
  11701. };
  11702. // File:src/materials/MeshBasicMaterial.js
  11703. /**
  11704. * @author mrdoob / http://mrdoob.com/
  11705. * @author alteredq / http://alteredqualia.com/
  11706. *
  11707. * parameters = {
  11708. * color: <hex>,
  11709. * opacity: <float>,
  11710. * map: new THREE.Texture( <Image> ),
  11711. *
  11712. * aoMap: new THREE.Texture( <Image> ),
  11713. * aoMapIntensity: <float>
  11714. *
  11715. * specularMap: new THREE.Texture( <Image> ),
  11716. *
  11717. * alphaMap: new THREE.Texture( <Image> ),
  11718. *
  11719. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11720. * combine: THREE.Multiply,
  11721. * reflectivity: <float>,
  11722. * refractionRatio: <float>,
  11723. *
  11724. * shading: THREE.SmoothShading,
  11725. * blending: THREE.NormalBlending,
  11726. * depthTest: <bool>,
  11727. * depthWrite: <bool>,
  11728. *
  11729. * wireframe: <boolean>,
  11730. * wireframeLinewidth: <float>,
  11731. *
  11732. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11733. *
  11734. * skinning: <bool>,
  11735. * morphTargets: <bool>,
  11736. *
  11737. * fog: <bool>
  11738. * }
  11739. */
  11740. THREE.MeshBasicMaterial = function ( parameters ) {
  11741. THREE.Material.call( this );
  11742. this.type = 'MeshBasicMaterial';
  11743. this.color = new THREE.Color( 0xffffff ); // emissive
  11744. this.map = null;
  11745. this.aoMap = null;
  11746. this.aoMapIntensity = 1.0;
  11747. this.specularMap = null;
  11748. this.alphaMap = null;
  11749. this.envMap = null;
  11750. this.combine = THREE.MultiplyOperation;
  11751. this.reflectivity = 1;
  11752. this.refractionRatio = 0.98;
  11753. this.fog = true;
  11754. this.shading = THREE.SmoothShading;
  11755. this.wireframe = false;
  11756. this.wireframeLinewidth = 1;
  11757. this.wireframeLinecap = 'round';
  11758. this.wireframeLinejoin = 'round';
  11759. this.vertexColors = THREE.NoColors;
  11760. this.skinning = false;
  11761. this.morphTargets = false;
  11762. this.setValues( parameters );
  11763. };
  11764. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11765. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  11766. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  11767. THREE.Material.prototype.copy.call( this, source );
  11768. this.color.copy( source.color );
  11769. this.map = source.map;
  11770. this.aoMap = source.aoMap;
  11771. this.aoMapIntensity = source.aoMapIntensity;
  11772. this.specularMap = source.specularMap;
  11773. this.alphaMap = source.alphaMap;
  11774. this.envMap = source.envMap;
  11775. this.combine = source.combine;
  11776. this.reflectivity = source.reflectivity;
  11777. this.refractionRatio = source.refractionRatio;
  11778. this.fog = source.fog;
  11779. this.shading = source.shading;
  11780. this.wireframe = source.wireframe;
  11781. this.wireframeLinewidth = source.wireframeLinewidth;
  11782. this.wireframeLinecap = source.wireframeLinecap;
  11783. this.wireframeLinejoin = source.wireframeLinejoin;
  11784. this.vertexColors = source.vertexColors;
  11785. this.skinning = source.skinning;
  11786. this.morphTargets = source.morphTargets;
  11787. return this;
  11788. };
  11789. // File:src/materials/MeshLambertMaterial.js
  11790. /**
  11791. * @author mrdoob / http://mrdoob.com/
  11792. * @author alteredq / http://alteredqualia.com/
  11793. *
  11794. * parameters = {
  11795. * color: <hex>,
  11796. * emissive: <hex>,
  11797. * opacity: <float>,
  11798. *
  11799. * map: new THREE.Texture( <Image> ),
  11800. *
  11801. * specularMap: new THREE.Texture( <Image> ),
  11802. *
  11803. * alphaMap: new THREE.Texture( <Image> ),
  11804. *
  11805. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11806. * combine: THREE.Multiply,
  11807. * reflectivity: <float>,
  11808. * refractionRatio: <float>,
  11809. *
  11810. * blending: THREE.NormalBlending,
  11811. * depthTest: <bool>,
  11812. * depthWrite: <bool>,
  11813. *
  11814. * wireframe: <boolean>,
  11815. * wireframeLinewidth: <float>,
  11816. *
  11817. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11818. *
  11819. * skinning: <bool>,
  11820. * morphTargets: <bool>,
  11821. * morphNormals: <bool>,
  11822. *
  11823. * fog: <bool>
  11824. * }
  11825. */
  11826. THREE.MeshLambertMaterial = function ( parameters ) {
  11827. THREE.Material.call( this );
  11828. this.type = 'MeshLambertMaterial';
  11829. this.color = new THREE.Color( 0xffffff ); // diffuse
  11830. this.emissive = new THREE.Color( 0x000000 );
  11831. this.map = null;
  11832. this.specularMap = null;
  11833. this.alphaMap = null;
  11834. this.envMap = null;
  11835. this.combine = THREE.MultiplyOperation;
  11836. this.reflectivity = 1;
  11837. this.refractionRatio = 0.98;
  11838. this.fog = true;
  11839. this.wireframe = false;
  11840. this.wireframeLinewidth = 1;
  11841. this.wireframeLinecap = 'round';
  11842. this.wireframeLinejoin = 'round';
  11843. this.vertexColors = THREE.NoColors;
  11844. this.skinning = false;
  11845. this.morphTargets = false;
  11846. this.morphNormals = false;
  11847. this.setValues( parameters );
  11848. };
  11849. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  11850. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  11851. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  11852. THREE.Material.prototype.copy.call( this, source );
  11853. this.color.copy( source.color );
  11854. this.emissive.copy( source.emissive );
  11855. this.map = source.map;
  11856. this.specularMap = source.specularMap;
  11857. this.alphaMap = source.alphaMap;
  11858. this.envMap = source.envMap;
  11859. this.combine = source.combine;
  11860. this.reflectivity = source.reflectivity;
  11861. this.refractionRatio = source.refractionRatio;
  11862. this.fog = source.fog;
  11863. this.wireframe = source.wireframe;
  11864. this.wireframeLinewidth = source.wireframeLinewidth;
  11865. this.wireframeLinecap = source.wireframeLinecap;
  11866. this.wireframeLinejoin = source.wireframeLinejoin;
  11867. this.vertexColors = source.vertexColors;
  11868. this.skinning = source.skinning;
  11869. this.morphTargets = source.morphTargets;
  11870. this.morphNormals = source.morphNormals;
  11871. return this;
  11872. };
  11873. // File:src/materials/MeshPhongMaterial.js
  11874. /**
  11875. * @author mrdoob / http://mrdoob.com/
  11876. * @author alteredq / http://alteredqualia.com/
  11877. *
  11878. * parameters = {
  11879. * color: <hex>,
  11880. * emissive: <hex>,
  11881. * specular: <hex>,
  11882. * shininess: <float>,
  11883. * opacity: <float>,
  11884. *
  11885. * map: new THREE.Texture( <Image> ),
  11886. *
  11887. * lightMap: new THREE.Texture( <Image> ),
  11888. * lightMapIntensity: <float>
  11889. *
  11890. * aoMap: new THREE.Texture( <Image> ),
  11891. * aoMapIntensity: <float>
  11892. *
  11893. * emissiveMap: new THREE.Texture( <Image> ),
  11894. *
  11895. * bumpMap: new THREE.Texture( <Image> ),
  11896. * bumpScale: <float>,
  11897. *
  11898. * normalMap: new THREE.Texture( <Image> ),
  11899. * normalScale: <Vector2>,
  11900. *
  11901. * displacementMap: new THREE.Texture( <Image> ),
  11902. * displacementScale: <float>,
  11903. * displacementBias: <float>,
  11904. *
  11905. * specularMap: new THREE.Texture( <Image> ),
  11906. *
  11907. * alphaMap: new THREE.Texture( <Image> ),
  11908. *
  11909. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11910. * combine: THREE.Multiply,
  11911. * reflectivity: <float>,
  11912. * refractionRatio: <float>,
  11913. *
  11914. * shading: THREE.SmoothShading,
  11915. * blending: THREE.NormalBlending,
  11916. * depthTest: <bool>,
  11917. * depthWrite: <bool>,
  11918. *
  11919. * wireframe: <boolean>,
  11920. * wireframeLinewidth: <float>,
  11921. *
  11922. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11923. *
  11924. * skinning: <bool>,
  11925. * morphTargets: <bool>,
  11926. * morphNormals: <bool>,
  11927. *
  11928. * fog: <bool>
  11929. * }
  11930. */
  11931. THREE.MeshPhongMaterial = function ( parameters ) {
  11932. THREE.Material.call( this );
  11933. this.type = 'MeshPhongMaterial';
  11934. this.color = new THREE.Color( 0xffffff ); // diffuse
  11935. this.emissive = new THREE.Color( 0x000000 );
  11936. this.specular = new THREE.Color( 0x111111 );
  11937. this.shininess = 30;
  11938. this.map = null;
  11939. this.lightMap = null;
  11940. this.lightMapIntensity = 1.0;
  11941. this.aoMap = null;
  11942. this.aoMapIntensity = 1.0;
  11943. this.emissiveMap = null;
  11944. this.bumpMap = null;
  11945. this.bumpScale = 1;
  11946. this.normalMap = null;
  11947. this.normalScale = new THREE.Vector2( 1, 1 );
  11948. this.displacementMap = null;
  11949. this.displacementScale = 1;
  11950. this.displacementBias = 0;
  11951. this.specularMap = null;
  11952. this.alphaMap = null;
  11953. this.envMap = null;
  11954. this.combine = THREE.MultiplyOperation;
  11955. this.reflectivity = 1;
  11956. this.refractionRatio = 0.98;
  11957. this.fog = true;
  11958. this.shading = THREE.SmoothShading;
  11959. this.wireframe = false;
  11960. this.wireframeLinewidth = 1;
  11961. this.wireframeLinecap = 'round';
  11962. this.wireframeLinejoin = 'round';
  11963. this.vertexColors = THREE.NoColors;
  11964. this.skinning = false;
  11965. this.morphTargets = false;
  11966. this.morphNormals = false;
  11967. this.setValues( parameters );
  11968. };
  11969. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  11970. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  11971. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  11972. THREE.Material.prototype.copy.call( this, source );
  11973. this.color.copy( source.color );
  11974. this.emissive.copy( source.emissive );
  11975. this.specular.copy( source.specular );
  11976. this.shininess = source.shininess;
  11977. this.map = source.map;
  11978. this.lightMap = source.lightMap;
  11979. this.lightMapIntensity = source.lightMapIntensity;
  11980. this.aoMap = source.aoMap;
  11981. this.aoMapIntensity = source.aoMapIntensity;
  11982. this.emissiveMap = source.emissiveMap;
  11983. this.bumpMap = source.bumpMap;
  11984. this.bumpScale = source.bumpScale;
  11985. this.normalMap = source.normalMap;
  11986. this.normalScale.copy( source.normalScale );
  11987. this.displacementMap = source.displacementMap;
  11988. this.displacementScale = source.displacementScale;
  11989. this.displacementBias = source.displacementBias;
  11990. this.specularMap = source.specularMap;
  11991. this.alphaMap = source.alphaMap;
  11992. this.envMap = source.envMap;
  11993. this.combine = source.combine;
  11994. this.reflectivity = source.reflectivity;
  11995. this.refractionRatio = source.refractionRatio;
  11996. this.fog = source.fog;
  11997. this.shading = source.shading;
  11998. this.wireframe = source.wireframe;
  11999. this.wireframeLinewidth = source.wireframeLinewidth;
  12000. this.wireframeLinecap = source.wireframeLinecap;
  12001. this.wireframeLinejoin = source.wireframeLinejoin;
  12002. this.vertexColors = source.vertexColors;
  12003. this.skinning = source.skinning;
  12004. this.morphTargets = source.morphTargets;
  12005. this.morphNormals = source.morphNormals;
  12006. return this;
  12007. };
  12008. // File:src/materials/MeshStandardMaterial.js
  12009. /**
  12010. * @author WestLangley / http://github.com/WestLangley
  12011. *
  12012. * parameters = {
  12013. * color: <hex>,
  12014. * roughness: <float>,
  12015. * reflectivity: <float>,
  12016. * metalness: <float>,
  12017. * emissive: <hex>,
  12018. * opacity: <float>,
  12019. *
  12020. * map: new THREE.Texture( <Image> ),
  12021. *
  12022. * lightMap: new THREE.Texture( <Image> ),
  12023. * lightMapIntensity: <float>
  12024. *
  12025. * aoMap: new THREE.Texture( <Image> ),
  12026. * aoMapIntensity: <float>
  12027. *
  12028. * emissiveMap: new THREE.Texture( <Image> ),
  12029. *
  12030. * bumpMap: new THREE.Texture( <Image> ),
  12031. * bumpScale: <float>,
  12032. *
  12033. * normalMap: new THREE.Texture( <Image> ),
  12034. * normalScale: <Vector2>,
  12035. *
  12036. * displacementMap: new THREE.Texture( <Image> ),
  12037. * displacementScale: <float>,
  12038. * displacementBias: <float>,
  12039. *
  12040. * roughnessMap: new THREE.Texture( <Image> ),
  12041. *
  12042. * reflectivityMap: new THREE.Texture( <Image> ),
  12043. *
  12044. * metalnessMap: new THREE.Texture( <Image> ),
  12045. *
  12046. * alphaMap: new THREE.Texture( <Image> ),
  12047. *
  12048. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12049. * envMapIntensity: <float>
  12050. *
  12051. * refractionRatio: <float>,
  12052. *
  12053. * shading: THREE.SmoothShading,
  12054. * blending: THREE.NormalBlending,
  12055. * depthTest: <bool>,
  12056. * depthWrite: <bool>,
  12057. *
  12058. * wireframe: <boolean>,
  12059. * wireframeLinewidth: <float>,
  12060. *
  12061. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12062. *
  12063. * skinning: <bool>,
  12064. * morphTargets: <bool>,
  12065. * morphNormals: <bool>,
  12066. *
  12067. * fog: <bool>
  12068. * }
  12069. */
  12070. THREE.MeshStandardMaterial = function ( parameters ) {
  12071. THREE.Material.call( this );
  12072. this.type = 'MeshStandardMaterial';
  12073. this.color = new THREE.Color( 0xffffff ); // diffuse
  12074. this.roughness = 0.5;
  12075. this.reflectivity = 1;
  12076. this.metalness = 0;
  12077. this.emissive = new THREE.Color( 0x000000 );
  12078. this.map = null;
  12079. this.lightMap = null;
  12080. this.lightMapIntensity = 1.0;
  12081. this.aoMap = null;
  12082. this.aoMapIntensity = 1.0;
  12083. this.emissiveMap = null;
  12084. this.bumpMap = null;
  12085. this.bumpScale = 1;
  12086. this.normalMap = null;
  12087. this.normalScale = new THREE.Vector2( 1, 1 );
  12088. this.displacementMap = null;
  12089. this.displacementScale = 1;
  12090. this.displacementBias = 0;
  12091. this.roughnessMap = null;
  12092. this.reflectivityMap = null;
  12093. this.metalnessMap = null;
  12094. this.alphaMap = null;
  12095. this.envMap = null;
  12096. this.envMapIntensity = 1.0;
  12097. this.refractionRatio = 0.98;
  12098. this.fog = true;
  12099. this.shading = THREE.SmoothShading;
  12100. this.wireframe = false;
  12101. this.wireframeLinewidth = 1;
  12102. this.wireframeLinecap = 'round';
  12103. this.wireframeLinejoin = 'round';
  12104. this.vertexColors = THREE.NoColors;
  12105. this.skinning = false;
  12106. this.morphTargets = false;
  12107. this.morphNormals = false;
  12108. this.setValues( parameters );
  12109. };
  12110. THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype );
  12111. THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial;
  12112. THREE.MeshStandardMaterial.prototype.copy = function ( source ) {
  12113. THREE.Material.prototype.copy.call( this, source );
  12114. this.color.copy( source.color );
  12115. this.roughness = source.roughness;
  12116. this.reflectivity = source.reflectivity;
  12117. this.metalness = source.metalness;
  12118. this.emissive.copy( source.emissive );
  12119. this.map = source.map;
  12120. this.lightMap = source.lightMap;
  12121. this.lightMapIntensity = source.lightMapIntensity;
  12122. this.aoMap = source.aoMap;
  12123. this.aoMapIntensity = source.aoMapIntensity;
  12124. this.emissiveMap = source.emissiveMap;
  12125. this.bumpMap = source.bumpMap;
  12126. this.bumpScale = source.bumpScale;
  12127. this.normalMap = source.normalMap;
  12128. this.normalScale.copy( source.normalScale );
  12129. this.displacementMap = source.displacementMap;
  12130. this.displacementScale = source.displacementScale;
  12131. this.displacementBias = source.displacementBias;
  12132. this.roughnessMap = source.roughnessMap;
  12133. this.reflectivityMap = source.reflectivityMap;
  12134. this.metalnessMap = source.metalnessMap;
  12135. this.alphaMap = source.alphaMap;
  12136. this.envMap = source.envMap;
  12137. this.envMapIntensity = source.envMapIntensity;
  12138. this.refractionRatio = source.refractionRatio;
  12139. this.fog = source.fog;
  12140. this.shading = source.shading;
  12141. this.wireframe = source.wireframe;
  12142. this.wireframeLinewidth = source.wireframeLinewidth;
  12143. this.wireframeLinecap = source.wireframeLinecap;
  12144. this.wireframeLinejoin = source.wireframeLinejoin;
  12145. this.vertexColors = source.vertexColors;
  12146. this.skinning = source.skinning;
  12147. this.morphTargets = source.morphTargets;
  12148. this.morphNormals = source.morphNormals;
  12149. return this;
  12150. };
  12151. // File:src/materials/MeshDepthMaterial.js
  12152. /**
  12153. * @author mrdoob / http://mrdoob.com/
  12154. * @author alteredq / http://alteredqualia.com/
  12155. *
  12156. * parameters = {
  12157. * opacity: <float>,
  12158. *
  12159. * blending: THREE.NormalBlending,
  12160. * depthTest: <bool>,
  12161. * depthWrite: <bool>,
  12162. *
  12163. * wireframe: <boolean>,
  12164. * wireframeLinewidth: <float>
  12165. * }
  12166. */
  12167. THREE.MeshDepthMaterial = function ( parameters ) {
  12168. THREE.Material.call( this );
  12169. this.type = 'MeshDepthMaterial';
  12170. this.morphTargets = false;
  12171. this.wireframe = false;
  12172. this.wireframeLinewidth = 1;
  12173. this.setValues( parameters );
  12174. };
  12175. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12176. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12177. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12178. THREE.Material.prototype.copy.call( this, source );
  12179. this.wireframe = source.wireframe;
  12180. this.wireframeLinewidth = source.wireframeLinewidth;
  12181. return this;
  12182. };
  12183. // File:src/materials/MeshNormalMaterial.js
  12184. /**
  12185. * @author mrdoob / http://mrdoob.com/
  12186. *
  12187. * parameters = {
  12188. * opacity: <float>,
  12189. *
  12190. * shading: THREE.FlatShading,
  12191. * blending: THREE.NormalBlending,
  12192. * depthTest: <bool>,
  12193. * depthWrite: <bool>,
  12194. *
  12195. * wireframe: <boolean>,
  12196. * wireframeLinewidth: <float>
  12197. * }
  12198. */
  12199. THREE.MeshNormalMaterial = function ( parameters ) {
  12200. THREE.Material.call( this, parameters );
  12201. this.type = 'MeshNormalMaterial';
  12202. this.wireframe = false;
  12203. this.wireframeLinewidth = 1;
  12204. this.morphTargets = false;
  12205. this.setValues( parameters );
  12206. };
  12207. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12208. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12209. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12210. THREE.Material.prototype.copy.call( this, source );
  12211. this.wireframe = source.wireframe;
  12212. this.wireframeLinewidth = source.wireframeLinewidth;
  12213. return this;
  12214. };
  12215. // File:src/materials/MultiMaterial.js
  12216. /**
  12217. * @author mrdoob / http://mrdoob.com/
  12218. */
  12219. THREE.MultiMaterial = function ( materials ) {
  12220. this.uuid = THREE.Math.generateUUID();
  12221. this.type = 'MultiMaterial';
  12222. this.materials = materials instanceof Array ? materials : [];
  12223. this.visible = true;
  12224. };
  12225. THREE.MultiMaterial.prototype = {
  12226. constructor: THREE.MultiMaterial,
  12227. toJSON: function ( meta ) {
  12228. var output = {
  12229. metadata: {
  12230. version: 4.2,
  12231. type: 'material',
  12232. generator: 'MaterialExporter'
  12233. },
  12234. uuid: this.uuid,
  12235. type: this.type,
  12236. materials: []
  12237. };
  12238. var materials = this.materials;
  12239. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12240. var material = materials[ i ].toJSON( meta );
  12241. delete material.metadata;
  12242. output.materials.push( material );
  12243. }
  12244. output.visible = this.visible;
  12245. return output;
  12246. },
  12247. clone: function () {
  12248. var material = new this.constructor();
  12249. for ( var i = 0; i < this.materials.length; i ++ ) {
  12250. material.materials.push( this.materials[ i ].clone() );
  12251. }
  12252. material.visible = this.visible;
  12253. return material;
  12254. }
  12255. };
  12256. // backwards compatibility
  12257. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  12258. // File:src/materials/PointsMaterial.js
  12259. /**
  12260. * @author mrdoob / http://mrdoob.com/
  12261. * @author alteredq / http://alteredqualia.com/
  12262. *
  12263. * parameters = {
  12264. * color: <hex>,
  12265. * opacity: <float>,
  12266. * map: new THREE.Texture( <Image> ),
  12267. *
  12268. * size: <float>,
  12269. * sizeAttenuation: <bool>,
  12270. *
  12271. * blending: THREE.NormalBlending,
  12272. * depthTest: <bool>,
  12273. * depthWrite: <bool>,
  12274. *
  12275. * vertexColors: <bool>,
  12276. *
  12277. * fog: <bool>
  12278. * }
  12279. */
  12280. THREE.PointsMaterial = function ( parameters ) {
  12281. THREE.Material.call( this );
  12282. this.type = 'PointsMaterial';
  12283. this.color = new THREE.Color( 0xffffff );
  12284. this.map = null;
  12285. this.size = 1;
  12286. this.sizeAttenuation = true;
  12287. this.vertexColors = THREE.NoColors;
  12288. this.fog = true;
  12289. this.setValues( parameters );
  12290. };
  12291. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12292. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12293. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12294. THREE.Material.prototype.copy.call( this, source );
  12295. this.color.copy( source.color );
  12296. this.map = source.map;
  12297. this.size = source.size;
  12298. this.sizeAttenuation = source.sizeAttenuation;
  12299. this.vertexColors = source.vertexColors;
  12300. this.fog = source.fog;
  12301. return this;
  12302. };
  12303. // File:src/materials/ShaderMaterial.js
  12304. /**
  12305. * @author alteredq / http://alteredqualia.com/
  12306. *
  12307. * parameters = {
  12308. * defines: { "label" : "value" },
  12309. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  12310. *
  12311. * fragmentShader: <string>,
  12312. * vertexShader: <string>,
  12313. *
  12314. * shading: THREE.SmoothShading,
  12315. * blending: THREE.NormalBlending,
  12316. * depthTest: <bool>,
  12317. * depthWrite: <bool>,
  12318. *
  12319. * wireframe: <boolean>,
  12320. * wireframeLinewidth: <float>,
  12321. *
  12322. * lights: <bool>,
  12323. *
  12324. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12325. *
  12326. * skinning: <bool>,
  12327. * morphTargets: <bool>,
  12328. * morphNormals: <bool>,
  12329. *
  12330. * fog: <bool>
  12331. * }
  12332. */
  12333. THREE.ShaderMaterial = function ( parameters ) {
  12334. THREE.Material.call( this );
  12335. this.type = 'ShaderMaterial';
  12336. this.defines = {};
  12337. this.uniforms = {};
  12338. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12339. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12340. this.shading = THREE.SmoothShading;
  12341. this.linewidth = 1;
  12342. this.wireframe = false;
  12343. this.wireframeLinewidth = 1;
  12344. this.fog = false; // set to use scene fog
  12345. this.lights = false; // set to use scene lights
  12346. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12347. this.skinning = false; // set to use skinning attribute streams
  12348. this.morphTargets = false; // set to use morph targets
  12349. this.morphNormals = false; // set to use morph normals
  12350. this.extensions = {
  12351. derivatives: false, // set to use derivatives
  12352. fragDepth: false, // set to use fragment depth values
  12353. drawBuffers: false, // set to use draw buffers
  12354. shaderTextureLOD: false // set to use shader texture LOD
  12355. };
  12356. // When rendered geometry doesn't include these attributes but the material does,
  12357. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12358. this.defaultAttributeValues = {
  12359. 'color': [ 1, 1, 1 ],
  12360. 'uv': [ 0, 0 ],
  12361. 'uv2': [ 0, 0 ]
  12362. };
  12363. this.index0AttributeName = undefined;
  12364. if ( parameters !== undefined ) {
  12365. if ( parameters.attributes !== undefined ) {
  12366. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12367. }
  12368. this.setValues( parameters );
  12369. }
  12370. };
  12371. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12372. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12373. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12374. THREE.Material.prototype.copy.call( this, source );
  12375. this.fragmentShader = source.fragmentShader;
  12376. this.vertexShader = source.vertexShader;
  12377. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12378. this.attributes = source.attributes;
  12379. this.defines = source.defines;
  12380. this.shading = source.shading;
  12381. this.wireframe = source.wireframe;
  12382. this.wireframeLinewidth = source.wireframeLinewidth;
  12383. this.fog = source.fog;
  12384. this.lights = source.lights;
  12385. this.vertexColors = source.vertexColors;
  12386. this.skinning = source.skinning;
  12387. this.morphTargets = source.morphTargets;
  12388. this.morphNormals = source.morphNormals;
  12389. this.extensions = source.extensions;
  12390. return this;
  12391. };
  12392. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12393. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12394. data.uniforms = this.uniforms;
  12395. data.attributes = this.attributes;
  12396. data.vertexShader = this.vertexShader;
  12397. data.fragmentShader = this.fragmentShader;
  12398. return data;
  12399. };
  12400. // File:src/materials/RawShaderMaterial.js
  12401. /**
  12402. * @author mrdoob / http://mrdoob.com/
  12403. */
  12404. THREE.RawShaderMaterial = function ( parameters ) {
  12405. THREE.ShaderMaterial.call( this, parameters );
  12406. this.type = 'RawShaderMaterial';
  12407. };
  12408. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12409. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12410. // File:src/materials/SpriteMaterial.js
  12411. /**
  12412. * @author alteredq / http://alteredqualia.com/
  12413. *
  12414. * parameters = {
  12415. * color: <hex>,
  12416. * opacity: <float>,
  12417. * map: new THREE.Texture( <Image> ),
  12418. *
  12419. * blending: THREE.NormalBlending,
  12420. * depthTest: <bool>,
  12421. * depthWrite: <bool>,
  12422. *
  12423. * uvOffset: new THREE.Vector2(),
  12424. * uvScale: new THREE.Vector2(),
  12425. *
  12426. * fog: <bool>
  12427. * }
  12428. */
  12429. THREE.SpriteMaterial = function ( parameters ) {
  12430. THREE.Material.call( this );
  12431. this.type = 'SpriteMaterial';
  12432. this.color = new THREE.Color( 0xffffff );
  12433. this.map = null;
  12434. this.rotation = 0;
  12435. this.fog = false;
  12436. // set parameters
  12437. this.setValues( parameters );
  12438. };
  12439. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12440. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12441. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12442. THREE.Material.prototype.copy.call( this, source );
  12443. this.color.copy( source.color );
  12444. this.map = source.map;
  12445. this.rotation = source.rotation;
  12446. this.fog = source.fog;
  12447. return this;
  12448. };
  12449. // File:src/textures/Texture.js
  12450. /**
  12451. * @author mrdoob / http://mrdoob.com/
  12452. * @author alteredq / http://alteredqualia.com/
  12453. * @author szimek / https://github.com/szimek/
  12454. */
  12455. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12456. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  12457. this.uuid = THREE.Math.generateUUID();
  12458. this.name = '';
  12459. this.sourceFile = '';
  12460. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  12461. this.mipmaps = [];
  12462. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  12463. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  12464. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  12465. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  12466. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  12467. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  12468. this.format = format !== undefined ? format : THREE.RGBAFormat;
  12469. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  12470. this.offset = new THREE.Vector2( 0, 0 );
  12471. this.repeat = new THREE.Vector2( 1, 1 );
  12472. this.generateMipmaps = true;
  12473. this.premultiplyAlpha = false;
  12474. this.flipY = true;
  12475. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  12476. this.version = 0;
  12477. this.onUpdate = null;
  12478. };
  12479. THREE.Texture.DEFAULT_IMAGE = undefined;
  12480. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  12481. THREE.Texture.prototype = {
  12482. constructor: THREE.Texture,
  12483. set needsUpdate ( value ) {
  12484. if ( value === true ) this.version ++;
  12485. },
  12486. clone: function () {
  12487. return new this.constructor().copy( this );
  12488. },
  12489. copy: function ( source ) {
  12490. this.image = source.image;
  12491. this.mipmaps = source.mipmaps.slice( 0 );
  12492. this.mapping = source.mapping;
  12493. this.wrapS = source.wrapS;
  12494. this.wrapT = source.wrapT;
  12495. this.magFilter = source.magFilter;
  12496. this.minFilter = source.minFilter;
  12497. this.anisotropy = source.anisotropy;
  12498. this.format = source.format;
  12499. this.type = source.type;
  12500. this.offset.copy( source.offset );
  12501. this.repeat.copy( source.repeat );
  12502. this.generateMipmaps = source.generateMipmaps;
  12503. this.premultiplyAlpha = source.premultiplyAlpha;
  12504. this.flipY = source.flipY;
  12505. this.unpackAlignment = source.unpackAlignment;
  12506. return this;
  12507. },
  12508. toJSON: function ( meta ) {
  12509. if ( meta.textures[ this.uuid ] !== undefined ) {
  12510. return meta.textures[ this.uuid ];
  12511. }
  12512. function getDataURL( image ) {
  12513. var canvas;
  12514. if ( image.toDataURL !== undefined ) {
  12515. canvas = image;
  12516. } else {
  12517. canvas = document.createElement( 'canvas' );
  12518. canvas.width = image.width;
  12519. canvas.height = image.height;
  12520. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  12521. }
  12522. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  12523. return canvas.toDataURL( 'image/jpeg', 0.6 );
  12524. } else {
  12525. return canvas.toDataURL( 'image/png' );
  12526. }
  12527. }
  12528. var output = {
  12529. metadata: {
  12530. version: 4.4,
  12531. type: 'Texture',
  12532. generator: 'Texture.toJSON'
  12533. },
  12534. uuid: this.uuid,
  12535. name: this.name,
  12536. mapping: this.mapping,
  12537. repeat: [ this.repeat.x, this.repeat.y ],
  12538. offset: [ this.offset.x, this.offset.y ],
  12539. wrap: [ this.wrapS, this.wrapT ],
  12540. minFilter: this.minFilter,
  12541. magFilter: this.magFilter,
  12542. anisotropy: this.anisotropy
  12543. };
  12544. if ( this.image !== undefined ) {
  12545. // TODO: Move to THREE.Image
  12546. var image = this.image;
  12547. if ( image.uuid === undefined ) {
  12548. image.uuid = THREE.Math.generateUUID(); // UGH
  12549. }
  12550. if ( meta.images[ image.uuid ] === undefined ) {
  12551. meta.images[ image.uuid ] = {
  12552. uuid: image.uuid,
  12553. url: getDataURL( image )
  12554. };
  12555. }
  12556. output.image = image.uuid;
  12557. }
  12558. meta.textures[ this.uuid ] = output;
  12559. return output;
  12560. },
  12561. dispose: function () {
  12562. this.dispatchEvent( { type: 'dispose' } );
  12563. },
  12564. transformUv: function ( uv ) {
  12565. if ( this.mapping !== THREE.UVMapping ) return;
  12566. uv.multiply( this.repeat );
  12567. uv.add( this.offset );
  12568. if ( uv.x < 0 || uv.x > 1 ) {
  12569. switch ( this.wrapS ) {
  12570. case THREE.RepeatWrapping:
  12571. uv.x = uv.x - Math.floor( uv.x );
  12572. break;
  12573. case THREE.ClampToEdgeWrapping:
  12574. uv.x = uv.x < 0 ? 0 : 1;
  12575. break;
  12576. case THREE.MirroredRepeatWrapping:
  12577. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  12578. uv.x = Math.ceil( uv.x ) - uv.x;
  12579. } else {
  12580. uv.x = uv.x - Math.floor( uv.x );
  12581. }
  12582. break;
  12583. }
  12584. }
  12585. if ( uv.y < 0 || uv.y > 1 ) {
  12586. switch ( this.wrapT ) {
  12587. case THREE.RepeatWrapping:
  12588. uv.y = uv.y - Math.floor( uv.y );
  12589. break;
  12590. case THREE.ClampToEdgeWrapping:
  12591. uv.y = uv.y < 0 ? 0 : 1;
  12592. break;
  12593. case THREE.MirroredRepeatWrapping:
  12594. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  12595. uv.y = Math.ceil( uv.y ) - uv.y;
  12596. } else {
  12597. uv.y = uv.y - Math.floor( uv.y );
  12598. }
  12599. break;
  12600. }
  12601. }
  12602. if ( this.flipY ) {
  12603. uv.y = 1 - uv.y;
  12604. }
  12605. }
  12606. };
  12607. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  12608. THREE.TextureIdCount = 0;
  12609. // File:src/textures/CanvasTexture.js
  12610. /**
  12611. * @author mrdoob / http://mrdoob.com/
  12612. */
  12613. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12614. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12615. this.needsUpdate = true;
  12616. };
  12617. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  12618. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  12619. // File:src/textures/CubeTexture.js
  12620. /**
  12621. * @author mrdoob / http://mrdoob.com/
  12622. */
  12623. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12624. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  12625. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12626. this.images = images;
  12627. this.flipY = false;
  12628. };
  12629. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  12630. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  12631. THREE.CubeTexture.prototype.copy = function ( source ) {
  12632. THREE.Texture.prototype.copy.call( this, source );
  12633. this.images = source.images;
  12634. return this;
  12635. };
  12636. // File:src/textures/CompressedTexture.js
  12637. /**
  12638. * @author alteredq / http://alteredqualia.com/
  12639. */
  12640. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12641. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12642. this.image = { width: width, height: height };
  12643. this.mipmaps = mipmaps;
  12644. // no flipping for cube textures
  12645. // (also flipping doesn't work for compressed textures )
  12646. this.flipY = false;
  12647. // can't generate mipmaps for compressed textures
  12648. // mips must be embedded in DDS files
  12649. this.generateMipmaps = false;
  12650. };
  12651. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  12652. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  12653. // File:src/textures/DataTexture.js
  12654. /**
  12655. * @author alteredq / http://alteredqualia.com/
  12656. */
  12657. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12658. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12659. this.image = { data: data, width: width, height: height };
  12660. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  12661. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  12662. this.flipY = false;
  12663. this.generateMipmaps = false;
  12664. };
  12665. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  12666. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  12667. // File:src/textures/VideoTexture.js
  12668. /**
  12669. * @author mrdoob / http://mrdoob.com/
  12670. */
  12671. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12672. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12673. this.generateMipmaps = false;
  12674. var scope = this;
  12675. function update() {
  12676. requestAnimationFrame( update );
  12677. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  12678. scope.needsUpdate = true;
  12679. }
  12680. }
  12681. update();
  12682. };
  12683. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  12684. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  12685. // File:src/objects/Group.js
  12686. /**
  12687. * @author mrdoob / http://mrdoob.com/
  12688. */
  12689. THREE.Group = function () {
  12690. THREE.Object3D.call( this );
  12691. this.type = 'Group';
  12692. };
  12693. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  12694. THREE.Group.prototype.constructor = THREE.Group;
  12695. // File:src/objects/Points.js
  12696. /**
  12697. * @author alteredq / http://alteredqualia.com/
  12698. */
  12699. THREE.Points = function ( geometry, material ) {
  12700. THREE.Object3D.call( this );
  12701. this.type = 'Points';
  12702. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12703. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  12704. };
  12705. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  12706. THREE.Points.prototype.constructor = THREE.Points;
  12707. THREE.Points.prototype.raycast = ( function () {
  12708. var inverseMatrix = new THREE.Matrix4();
  12709. var ray = new THREE.Ray();
  12710. return function raycast( raycaster, intersects ) {
  12711. var object = this;
  12712. var geometry = object.geometry;
  12713. var threshold = raycaster.params.Points.threshold;
  12714. inverseMatrix.getInverse( this.matrixWorld );
  12715. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12716. if ( geometry.boundingBox !== null ) {
  12717. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12718. }
  12719. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12720. var localThresholdSq = localThreshold * localThreshold;
  12721. var position = new THREE.Vector3();
  12722. function testPoint( point, index ) {
  12723. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  12724. if ( rayPointDistanceSq < localThresholdSq ) {
  12725. var intersectPoint = ray.closestPointToPoint( point );
  12726. intersectPoint.applyMatrix4( object.matrixWorld );
  12727. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12728. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12729. intersects.push( {
  12730. distance: distance,
  12731. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12732. point: intersectPoint.clone(),
  12733. index: index,
  12734. face: null,
  12735. object: object
  12736. } );
  12737. }
  12738. }
  12739. if ( geometry instanceof THREE.BufferGeometry ) {
  12740. var index = geometry.index;
  12741. var attributes = geometry.attributes;
  12742. var positions = attributes.position.array;
  12743. if ( index !== null ) {
  12744. var indices = index.array;
  12745. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  12746. var a = indices[ i ];
  12747. position.fromArray( positions, a * 3 );
  12748. testPoint( position, a );
  12749. }
  12750. } else {
  12751. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  12752. position.fromArray( positions, i * 3 );
  12753. testPoint( position, i );
  12754. }
  12755. }
  12756. } else {
  12757. var vertices = geometry.vertices;
  12758. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  12759. testPoint( vertices[ i ], i );
  12760. }
  12761. }
  12762. };
  12763. }() );
  12764. THREE.Points.prototype.clone = function () {
  12765. return new this.constructor( this.geometry, this.material ).copy( this );
  12766. };
  12767. // File:src/objects/Line.js
  12768. /**
  12769. * @author mrdoob / http://mrdoob.com/
  12770. */
  12771. THREE.Line = function ( geometry, material, mode ) {
  12772. if ( mode === 1 ) {
  12773. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  12774. return new THREE.LineSegments( geometry, material );
  12775. }
  12776. THREE.Object3D.call( this );
  12777. this.type = 'Line';
  12778. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12779. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  12780. };
  12781. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  12782. THREE.Line.prototype.constructor = THREE.Line;
  12783. THREE.Line.prototype.raycast = ( function () {
  12784. var inverseMatrix = new THREE.Matrix4();
  12785. var ray = new THREE.Ray();
  12786. var sphere = new THREE.Sphere();
  12787. return function raycast( raycaster, intersects ) {
  12788. var precision = raycaster.linePrecision;
  12789. var precisionSq = precision * precision;
  12790. var geometry = this.geometry;
  12791. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12792. // Checking boundingSphere distance to ray
  12793. sphere.copy( geometry.boundingSphere );
  12794. sphere.applyMatrix4( this.matrixWorld );
  12795. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12796. inverseMatrix.getInverse( this.matrixWorld );
  12797. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12798. var vStart = new THREE.Vector3();
  12799. var vEnd = new THREE.Vector3();
  12800. var interSegment = new THREE.Vector3();
  12801. var interRay = new THREE.Vector3();
  12802. var step = this instanceof THREE.LineSegments ? 2 : 1;
  12803. if ( geometry instanceof THREE.BufferGeometry ) {
  12804. var index = geometry.index;
  12805. var attributes = geometry.attributes;
  12806. if ( index !== null ) {
  12807. var indices = index.array;
  12808. var positions = attributes.position.array;
  12809. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  12810. var a = indices[ i ];
  12811. var b = indices[ i + 1 ];
  12812. vStart.fromArray( positions, a * 3 );
  12813. vEnd.fromArray( positions, b * 3 );
  12814. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12815. if ( distSq > precisionSq ) continue;
  12816. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12817. var distance = raycaster.ray.origin.distanceTo( interRay );
  12818. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12819. intersects.push( {
  12820. distance: distance,
  12821. // What do we want? intersection point on the ray or on the segment??
  12822. // point: raycaster.ray.at( distance ),
  12823. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12824. index: i,
  12825. face: null,
  12826. faceIndex: null,
  12827. object: this
  12828. } );
  12829. }
  12830. } else {
  12831. var positions = attributes.position.array;
  12832. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  12833. vStart.fromArray( positions, 3 * i );
  12834. vEnd.fromArray( positions, 3 * i + 3 );
  12835. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12836. if ( distSq > precisionSq ) continue;
  12837. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12838. var distance = raycaster.ray.origin.distanceTo( interRay );
  12839. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12840. intersects.push( {
  12841. distance: distance,
  12842. // What do we want? intersection point on the ray or on the segment??
  12843. // point: raycaster.ray.at( distance ),
  12844. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12845. index: i,
  12846. face: null,
  12847. faceIndex: null,
  12848. object: this
  12849. } );
  12850. }
  12851. }
  12852. } else if ( geometry instanceof THREE.Geometry ) {
  12853. var vertices = geometry.vertices;
  12854. var nbVertices = vertices.length;
  12855. for ( var i = 0; i < nbVertices - 1; i += step ) {
  12856. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  12857. if ( distSq > precisionSq ) continue;
  12858. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12859. var distance = raycaster.ray.origin.distanceTo( interRay );
  12860. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12861. intersects.push( {
  12862. distance: distance,
  12863. // What do we want? intersection point on the ray or on the segment??
  12864. // point: raycaster.ray.at( distance ),
  12865. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12866. index: i,
  12867. face: null,
  12868. faceIndex: null,
  12869. object: this
  12870. } );
  12871. }
  12872. }
  12873. };
  12874. }() );
  12875. THREE.Line.prototype.clone = function () {
  12876. return new this.constructor( this.geometry, this.material ).copy( this );
  12877. };
  12878. // DEPRECATED
  12879. THREE.LineStrip = 0;
  12880. THREE.LinePieces = 1;
  12881. // File:src/objects/LineSegments.js
  12882. /**
  12883. * @author mrdoob / http://mrdoob.com/
  12884. */
  12885. THREE.LineSegments = function ( geometry, material ) {
  12886. THREE.Line.call( this, geometry, material );
  12887. this.type = 'LineSegments';
  12888. };
  12889. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  12890. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  12891. // File:src/objects/Mesh.js
  12892. /**
  12893. * @author mrdoob / http://mrdoob.com/
  12894. * @author alteredq / http://alteredqualia.com/
  12895. * @author mikael emtinger / http://gomo.se/
  12896. * @author jonobr1 / http://jonobr1.com/
  12897. */
  12898. THREE.Mesh = function ( geometry, material ) {
  12899. THREE.Object3D.call( this );
  12900. this.type = 'Mesh';
  12901. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12902. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12903. this.drawMode = THREE.TrianglesDrawMode;
  12904. this.updateMorphTargets();
  12905. };
  12906. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  12907. THREE.Mesh.prototype.constructor = THREE.Mesh;
  12908. THREE.Mesh.prototype.setDrawMode = function ( value ) {
  12909. this.drawMode = value;
  12910. };
  12911. THREE.Mesh.prototype.updateMorphTargets = function () {
  12912. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  12913. this.morphTargetBase = - 1;
  12914. this.morphTargetInfluences = [];
  12915. this.morphTargetDictionary = {};
  12916. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  12917. this.morphTargetInfluences.push( 0 );
  12918. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  12919. }
  12920. }
  12921. };
  12922. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  12923. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  12924. return this.morphTargetDictionary[ name ];
  12925. }
  12926. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  12927. return 0;
  12928. };
  12929. THREE.Mesh.prototype.raycast = ( function () {
  12930. var inverseMatrix = new THREE.Matrix4();
  12931. var ray = new THREE.Ray();
  12932. var sphere = new THREE.Sphere();
  12933. var vA = new THREE.Vector3();
  12934. var vB = new THREE.Vector3();
  12935. var vC = new THREE.Vector3();
  12936. var tempA = new THREE.Vector3();
  12937. var tempB = new THREE.Vector3();
  12938. var tempC = new THREE.Vector3();
  12939. var uvA = new THREE.Vector2();
  12940. var uvB = new THREE.Vector2();
  12941. var uvC = new THREE.Vector2();
  12942. var barycoord = new THREE.Vector3();
  12943. var intersectionPoint = new THREE.Vector3();
  12944. var intersectionPointWorld = new THREE.Vector3();
  12945. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  12946. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  12947. uv1.multiplyScalar( barycoord.x );
  12948. uv2.multiplyScalar( barycoord.y );
  12949. uv3.multiplyScalar( barycoord.z );
  12950. uv1.add( uv2 ).add( uv3 );
  12951. return uv1.clone();
  12952. }
  12953. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ){
  12954. var intersect;
  12955. var material = object.material;
  12956. if ( material.side === THREE.BackSide ) {
  12957. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12958. } else {
  12959. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  12960. }
  12961. if ( intersect === null ) return null;
  12962. intersectionPointWorld.copy( point );
  12963. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12964. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  12965. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12966. return {
  12967. distance: distance,
  12968. point: intersectionPointWorld.clone(),
  12969. object: object
  12970. };
  12971. }
  12972. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  12973. vA.fromArray( positions, a * 3 );
  12974. vB.fromArray( positions, b * 3 );
  12975. vC.fromArray( positions, c * 3 );
  12976. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  12977. if ( intersection ) {
  12978. if ( uvs ) {
  12979. uvA.fromArray( uvs, a * 2 );
  12980. uvB.fromArray( uvs, b * 2 );
  12981. uvC.fromArray( uvs, c * 2 );
  12982. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  12983. }
  12984. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  12985. intersection.faceIndex = a;
  12986. }
  12987. return intersection;
  12988. }
  12989. return function raycast( raycaster, intersects ) {
  12990. var geometry = this.geometry;
  12991. var material = this.material;
  12992. if ( material === undefined ) return;
  12993. // Checking boundingSphere distance to ray
  12994. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12995. var matrixWorld = this.matrixWorld;
  12996. sphere.copy( geometry.boundingSphere );
  12997. sphere.applyMatrix4( matrixWorld );
  12998. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12999. // Check boundingBox before continuing
  13000. inverseMatrix.getInverse( matrixWorld );
  13001. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13002. if ( geometry.boundingBox !== null ) {
  13003. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13004. }
  13005. var uvs, intersection;
  13006. if ( geometry instanceof THREE.BufferGeometry ) {
  13007. var a, b, c;
  13008. var index = geometry.index;
  13009. var attributes = geometry.attributes;
  13010. var positions = attributes.position.array;
  13011. if ( attributes.uv !== undefined ){
  13012. uvs = attributes.uv.array;
  13013. }
  13014. if ( index !== null ) {
  13015. var indices = index.array;
  13016. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13017. a = indices[ i ];
  13018. b = indices[ i + 1 ];
  13019. c = indices[ i + 2 ];
  13020. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13021. if ( intersection ) {
  13022. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13023. intersects.push( intersection );
  13024. }
  13025. }
  13026. } else {
  13027. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13028. a = i / 3;
  13029. b = a + 1;
  13030. c = a + 2;
  13031. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13032. if ( intersection ) {
  13033. intersection.index = a; // triangle number in positions buffer semantics
  13034. intersects.push( intersection );
  13035. }
  13036. }
  13037. }
  13038. } else if ( geometry instanceof THREE.Geometry ) {
  13039. var fvA, fvB, fvC;
  13040. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13041. var materials = isFaceMaterial === true ? material.materials : null;
  13042. var vertices = geometry.vertices;
  13043. var faces = geometry.faces;
  13044. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13045. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13046. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13047. var face = faces[ f ];
  13048. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13049. if ( faceMaterial === undefined ) continue;
  13050. fvA = vertices[ face.a ];
  13051. fvB = vertices[ face.b ];
  13052. fvC = vertices[ face.c ];
  13053. if ( faceMaterial.morphTargets === true ) {
  13054. var morphTargets = geometry.morphTargets;
  13055. var morphInfluences = this.morphTargetInfluences;
  13056. vA.set( 0, 0, 0 );
  13057. vB.set( 0, 0, 0 );
  13058. vC.set( 0, 0, 0 );
  13059. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13060. var influence = morphInfluences[ t ];
  13061. if ( influence === 0 ) continue;
  13062. var targets = morphTargets[ t ].vertices;
  13063. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13064. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13065. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13066. }
  13067. vA.add( fvA );
  13068. vB.add( fvB );
  13069. vC.add( fvC );
  13070. fvA = vA;
  13071. fvB = vB;
  13072. fvC = vC;
  13073. }
  13074. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13075. if ( intersection ) {
  13076. if ( uvs ) {
  13077. var uvs_f = uvs[ f ];
  13078. uvA.copy( uvs_f[ 0 ] );
  13079. uvB.copy( uvs_f[ 1 ] );
  13080. uvC.copy( uvs_f[ 2 ] );
  13081. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13082. }
  13083. intersection.face = face;
  13084. intersection.faceIndex = f;
  13085. intersects.push( intersection );
  13086. }
  13087. }
  13088. }
  13089. };
  13090. }() );
  13091. THREE.Mesh.prototype.clone = function () {
  13092. return new this.constructor( this.geometry, this.material ).copy( this );
  13093. };
  13094. // File:src/objects/Bone.js
  13095. /**
  13096. * @author mikael emtinger / http://gomo.se/
  13097. * @author alteredq / http://alteredqualia.com/
  13098. * @author ikerr / http://verold.com
  13099. */
  13100. THREE.Bone = function ( skin ) {
  13101. THREE.Object3D.call( this );
  13102. this.type = 'Bone';
  13103. this.skin = skin;
  13104. };
  13105. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13106. THREE.Bone.prototype.constructor = THREE.Bone;
  13107. THREE.Bone.prototype.copy = function ( source ) {
  13108. THREE.Object3D.prototype.copy.call( this, source );
  13109. this.skin = source.skin;
  13110. return this;
  13111. };
  13112. // File:src/objects/Skeleton.js
  13113. /**
  13114. * @author mikael emtinger / http://gomo.se/
  13115. * @author alteredq / http://alteredqualia.com/
  13116. * @author michael guerrero / http://realitymeltdown.com
  13117. * @author ikerr / http://verold.com
  13118. */
  13119. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13120. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13121. this.identityMatrix = new THREE.Matrix4();
  13122. // copy the bone array
  13123. bones = bones || [];
  13124. this.bones = bones.slice( 0 );
  13125. // create a bone texture or an array of floats
  13126. if ( this.useVertexTexture ) {
  13127. // layout (1 matrix = 4 pixels)
  13128. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13129. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13130. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13131. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13132. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13133. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13134. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13135. size = Math.max( size, 4 );
  13136. this.boneTextureWidth = size;
  13137. this.boneTextureHeight = size;
  13138. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13139. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13140. } else {
  13141. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13142. }
  13143. // use the supplied bone inverses or calculate the inverses
  13144. if ( boneInverses === undefined ) {
  13145. this.calculateInverses();
  13146. } else {
  13147. if ( this.bones.length === boneInverses.length ) {
  13148. this.boneInverses = boneInverses.slice( 0 );
  13149. } else {
  13150. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13151. this.boneInverses = [];
  13152. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13153. this.boneInverses.push( new THREE.Matrix4() );
  13154. }
  13155. }
  13156. }
  13157. };
  13158. THREE.Skeleton.prototype.calculateInverses = function () {
  13159. this.boneInverses = [];
  13160. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13161. var inverse = new THREE.Matrix4();
  13162. if ( this.bones[ b ] ) {
  13163. inverse.getInverse( this.bones[ b ].matrixWorld );
  13164. }
  13165. this.boneInverses.push( inverse );
  13166. }
  13167. };
  13168. THREE.Skeleton.prototype.pose = function () {
  13169. var bone;
  13170. // recover the bind-time world matrices
  13171. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13172. bone = this.bones[ b ];
  13173. if ( bone ) {
  13174. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13175. }
  13176. }
  13177. // compute the local matrices, positions, rotations and scales
  13178. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13179. bone = this.bones[ b ];
  13180. if ( bone ) {
  13181. if ( bone.parent ) {
  13182. bone.matrix.getInverse( bone.parent.matrixWorld );
  13183. bone.matrix.multiply( bone.matrixWorld );
  13184. } else {
  13185. bone.matrix.copy( bone.matrixWorld );
  13186. }
  13187. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13188. }
  13189. }
  13190. };
  13191. THREE.Skeleton.prototype.update = ( function () {
  13192. var offsetMatrix = new THREE.Matrix4();
  13193. return function update() {
  13194. // flatten bone matrices to array
  13195. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13196. // compute the offset between the current and the original transform
  13197. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13198. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13199. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  13200. }
  13201. if ( this.useVertexTexture ) {
  13202. this.boneTexture.needsUpdate = true;
  13203. }
  13204. };
  13205. } )();
  13206. THREE.Skeleton.prototype.clone = function () {
  13207. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13208. };
  13209. // File:src/objects/SkinnedMesh.js
  13210. /**
  13211. * @author mikael emtinger / http://gomo.se/
  13212. * @author alteredq / http://alteredqualia.com/
  13213. * @author ikerr / http://verold.com
  13214. */
  13215. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13216. THREE.Mesh.call( this, geometry, material );
  13217. this.type = 'SkinnedMesh';
  13218. this.bindMode = "attached";
  13219. this.bindMatrix = new THREE.Matrix4();
  13220. this.bindMatrixInverse = new THREE.Matrix4();
  13221. // init bones
  13222. // TODO: remove bone creation as there is no reason (other than
  13223. // convenience) for THREE.SkinnedMesh to do this.
  13224. var bones = [];
  13225. if ( this.geometry && this.geometry.bones !== undefined ) {
  13226. var bone, gbone;
  13227. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13228. gbone = this.geometry.bones[ b ];
  13229. bone = new THREE.Bone( this );
  13230. bones.push( bone );
  13231. bone.name = gbone.name;
  13232. bone.position.fromArray( gbone.pos );
  13233. bone.quaternion.fromArray( gbone.rotq );
  13234. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13235. }
  13236. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13237. gbone = this.geometry.bones[ b ];
  13238. if ( gbone.parent !== - 1 && gbone.parent !== null) {
  13239. bones[ gbone.parent ].add( bones[ b ] );
  13240. } else {
  13241. this.add( bones[ b ] );
  13242. }
  13243. }
  13244. }
  13245. this.normalizeSkinWeights();
  13246. this.updateMatrixWorld( true );
  13247. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13248. };
  13249. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13250. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13251. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13252. this.skeleton = skeleton;
  13253. if ( bindMatrix === undefined ) {
  13254. this.updateMatrixWorld( true );
  13255. this.skeleton.calculateInverses();
  13256. bindMatrix = this.matrixWorld;
  13257. }
  13258. this.bindMatrix.copy( bindMatrix );
  13259. this.bindMatrixInverse.getInverse( bindMatrix );
  13260. };
  13261. THREE.SkinnedMesh.prototype.pose = function () {
  13262. this.skeleton.pose();
  13263. };
  13264. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13265. if ( this.geometry instanceof THREE.Geometry ) {
  13266. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  13267. var sw = this.geometry.skinWeights[ i ];
  13268. var scale = 1.0 / sw.lengthManhattan();
  13269. if ( scale !== Infinity ) {
  13270. sw.multiplyScalar( scale );
  13271. } else {
  13272. sw.set( 1 ); // this will be normalized by the shader anyway
  13273. }
  13274. }
  13275. } else {
  13276. // skinning weights assumed to be normalized for THREE.BufferGeometry
  13277. }
  13278. };
  13279. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13280. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13281. if ( this.bindMode === "attached" ) {
  13282. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13283. } else if ( this.bindMode === "detached" ) {
  13284. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13285. } else {
  13286. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13287. }
  13288. };
  13289. THREE.SkinnedMesh.prototype.clone = function() {
  13290. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13291. };
  13292. // File:src/objects/LOD.js
  13293. /**
  13294. * @author mikael emtinger / http://gomo.se/
  13295. * @author alteredq / http://alteredqualia.com/
  13296. * @author mrdoob / http://mrdoob.com/
  13297. */
  13298. THREE.LOD = function () {
  13299. THREE.Object3D.call( this );
  13300. this.type = 'LOD';
  13301. Object.defineProperties( this, {
  13302. levels: {
  13303. enumerable: true,
  13304. value: []
  13305. },
  13306. objects: {
  13307. get: function () {
  13308. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  13309. return this.levels;
  13310. }
  13311. }
  13312. } );
  13313. };
  13314. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13315. THREE.LOD.prototype.constructor = THREE.LOD;
  13316. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13317. if ( distance === undefined ) distance = 0;
  13318. distance = Math.abs( distance );
  13319. var levels = this.levels;
  13320. for ( var l = 0; l < levels.length; l ++ ) {
  13321. if ( distance < levels[ l ].distance ) {
  13322. break;
  13323. }
  13324. }
  13325. levels.splice( l, 0, { distance: distance, object: object } );
  13326. this.add( object );
  13327. };
  13328. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13329. var levels = this.levels;
  13330. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13331. if ( distance < levels[ i ].distance ) {
  13332. break;
  13333. }
  13334. }
  13335. return levels[ i - 1 ].object;
  13336. };
  13337. THREE.LOD.prototype.raycast = ( function () {
  13338. var matrixPosition = new THREE.Vector3();
  13339. return function raycast( raycaster, intersects ) {
  13340. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13341. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13342. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13343. };
  13344. }() );
  13345. THREE.LOD.prototype.update = function () {
  13346. var v1 = new THREE.Vector3();
  13347. var v2 = new THREE.Vector3();
  13348. return function update( camera ) {
  13349. var levels = this.levels;
  13350. if ( levels.length > 1 ) {
  13351. v1.setFromMatrixPosition( camera.matrixWorld );
  13352. v2.setFromMatrixPosition( this.matrixWorld );
  13353. var distance = v1.distanceTo( v2 );
  13354. levels[ 0 ].object.visible = true;
  13355. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13356. if ( distance >= levels[ i ].distance ) {
  13357. levels[ i - 1 ].object.visible = false;
  13358. levels[ i ].object.visible = true;
  13359. } else {
  13360. break;
  13361. }
  13362. }
  13363. for ( ; i < l; i ++ ) {
  13364. levels[ i ].object.visible = false;
  13365. }
  13366. }
  13367. };
  13368. }();
  13369. THREE.LOD.prototype.copy = function ( source ) {
  13370. THREE.Object3D.prototype.copy.call( this, source, false );
  13371. var levels = source.levels;
  13372. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13373. var level = levels[ i ];
  13374. this.addLevel( level.object.clone(), level.distance );
  13375. }
  13376. return this;
  13377. };
  13378. THREE.LOD.prototype.toJSON = function ( meta ) {
  13379. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13380. data.object.levels = [];
  13381. var levels = this.levels;
  13382. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13383. var level = levels[ i ];
  13384. data.object.levels.push( {
  13385. object: level.object.uuid,
  13386. distance: level.distance
  13387. } );
  13388. }
  13389. return data;
  13390. };
  13391. // File:src/objects/Sprite.js
  13392. /**
  13393. * @author mikael emtinger / http://gomo.se/
  13394. * @author alteredq / http://alteredqualia.com/
  13395. */
  13396. THREE.Sprite = ( function () {
  13397. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13398. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13399. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13400. var geometry = new THREE.BufferGeometry();
  13401. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13402. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13403. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13404. return function Sprite( material ) {
  13405. THREE.Object3D.call( this );
  13406. this.type = 'Sprite';
  13407. this.geometry = geometry;
  13408. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13409. };
  13410. } )();
  13411. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13412. THREE.Sprite.prototype.constructor = THREE.Sprite;
  13413. THREE.Sprite.prototype.raycast = ( function () {
  13414. var matrixPosition = new THREE.Vector3();
  13415. return function raycast( raycaster, intersects ) {
  13416. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13417. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13418. var guessSizeSq = this.scale.x * this.scale.y;
  13419. if ( distanceSq > guessSizeSq ) {
  13420. return;
  13421. }
  13422. intersects.push( {
  13423. distance: Math.sqrt( distanceSq ),
  13424. point: this.position,
  13425. face: null,
  13426. object: this
  13427. } );
  13428. };
  13429. }() );
  13430. THREE.Sprite.prototype.clone = function () {
  13431. return new this.constructor( this.material ).copy( this );
  13432. };
  13433. // Backwards compatibility
  13434. THREE.Particle = THREE.Sprite;
  13435. // File:src/objects/LensFlare.js
  13436. /**
  13437. * @author mikael emtinger / http://gomo.se/
  13438. * @author alteredq / http://alteredqualia.com/
  13439. */
  13440. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  13441. THREE.Object3D.call( this );
  13442. this.lensFlares = [];
  13443. this.positionScreen = new THREE.Vector3();
  13444. this.customUpdateCallback = undefined;
  13445. if ( texture !== undefined ) {
  13446. this.add( texture, size, distance, blending, color );
  13447. }
  13448. };
  13449. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  13450. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  13451. /*
  13452. * Add: adds another flare
  13453. */
  13454. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  13455. if ( size === undefined ) size = - 1;
  13456. if ( distance === undefined ) distance = 0;
  13457. if ( opacity === undefined ) opacity = 1;
  13458. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  13459. if ( blending === undefined ) blending = THREE.NormalBlending;
  13460. distance = Math.min( distance, Math.max( 0, distance ) );
  13461. this.lensFlares.push( {
  13462. texture: texture, // THREE.Texture
  13463. size: size, // size in pixels (-1 = use texture.width)
  13464. distance: distance, // distance (0-1) from light source (0=at light source)
  13465. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13466. scale: 1, // scale
  13467. rotation: 0, // rotation
  13468. opacity: opacity, // opacity
  13469. color: color, // color
  13470. blending: blending // blending
  13471. } );
  13472. };
  13473. /*
  13474. * Update lens flares update positions on all flares based on the screen position
  13475. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13476. */
  13477. THREE.LensFlare.prototype.updateLensFlares = function () {
  13478. var f, fl = this.lensFlares.length;
  13479. var flare;
  13480. var vecX = - this.positionScreen.x * 2;
  13481. var vecY = - this.positionScreen.y * 2;
  13482. for ( f = 0; f < fl; f ++ ) {
  13483. flare = this.lensFlares[ f ];
  13484. flare.x = this.positionScreen.x + vecX * flare.distance;
  13485. flare.y = this.positionScreen.y + vecY * flare.distance;
  13486. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13487. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13488. }
  13489. };
  13490. THREE.LensFlare.prototype.copy = function ( source ) {
  13491. THREE.Object3D.prototype.copy.call( this, source );
  13492. this.positionScreen.copy( source.positionScreen );
  13493. this.customUpdateCallback = source.customUpdateCallback;
  13494. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13495. this.lensFlares.push( source.lensFlares[ i ] );
  13496. }
  13497. return this;
  13498. };
  13499. // File:src/scenes/Scene.js
  13500. /**
  13501. * @author mrdoob / http://mrdoob.com/
  13502. */
  13503. THREE.Scene = function () {
  13504. THREE.Object3D.call( this );
  13505. this.type = 'Scene';
  13506. this.fog = null;
  13507. this.overrideMaterial = null;
  13508. this.autoUpdate = true; // checked by the renderer
  13509. };
  13510. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  13511. THREE.Scene.prototype.constructor = THREE.Scene;
  13512. THREE.Scene.prototype.copy = function ( source ) {
  13513. THREE.Object3D.prototype.copy.call( this, source );
  13514. if ( source.fog !== null ) this.fog = source.fog.clone();
  13515. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13516. this.autoUpdate = source.autoUpdate;
  13517. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13518. return this;
  13519. };
  13520. // File:src/scenes/Fog.js
  13521. /**
  13522. * @author mrdoob / http://mrdoob.com/
  13523. * @author alteredq / http://alteredqualia.com/
  13524. */
  13525. THREE.Fog = function ( color, near, far ) {
  13526. this.name = '';
  13527. this.color = new THREE.Color( color );
  13528. this.near = ( near !== undefined ) ? near : 1;
  13529. this.far = ( far !== undefined ) ? far : 1000;
  13530. };
  13531. THREE.Fog.prototype.clone = function () {
  13532. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  13533. };
  13534. // File:src/scenes/FogExp2.js
  13535. /**
  13536. * @author mrdoob / http://mrdoob.com/
  13537. * @author alteredq / http://alteredqualia.com/
  13538. */
  13539. THREE.FogExp2 = function ( color, density ) {
  13540. this.name = '';
  13541. this.color = new THREE.Color( color );
  13542. this.density = ( density !== undefined ) ? density : 0.00025;
  13543. };
  13544. THREE.FogExp2.prototype.clone = function () {
  13545. return new THREE.FogExp2( this.color.getHex(), this.density );
  13546. };
  13547. // File:src/renderers/shaders/ShaderChunk.js
  13548. THREE.ShaderChunk = {};
  13549. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  13550. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  13551. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  13552. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  13553. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  13554. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  13555. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  13556. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n reflectedLight.indirectDiffuse *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n#endif\n";
  13557. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  13558. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  13559. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  13560. THREE.ShaderChunk[ 'begin_vertex'] = "\nvec3 transformed = vec3( position );\n";
  13561. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  13562. THREE.ShaderChunk[ 'beginnormal_vertex'] = "\nvec3 objectNormal = vec3( normal );\n";
  13563. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  13564. THREE.ShaderChunk[ 'bsdfs'] = "float calcLightAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55437 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = alpha * alpha;\n float gl = dotNL + pow( a2 + ( 1.0 - a2 ) * dotNL * dotNL, 0.5 );\n float gv = dotNV + pow( a2 + ( 1.0 - a2 ) * dotNV * dotNV, 0.5 );\n return 1.0 / ( gl * gv );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = alpha * alpha;\n float denom = dotNH * dotNH * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / ( denom * denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float alpha = roughness * roughness;\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_Smith( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n return ( 2.0 / square( ggxRoughness + 0.0001 ) - 2.0 );\n}";
  13565. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  13566. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n";
  13567. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  13568. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  13569. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  13570. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  13571. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  13572. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  13573. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  13574. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  13575. // File:src/renderers/shaders/ShaderChunk/common.glsl
  13576. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat square( const in float x ) { return x*x; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n float distance = dot( planeNormal, point - pointOnPlane );\n return - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nvec3 inputToLinear( in vec3 a ) {\n #ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\nvec3 linearToOutput( in vec3 a ) {\n #ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\n";
  13577. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  13578. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  13579. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  13580. THREE.ShaderChunk[ 'displacementmap_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  13581. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  13582. THREE.ShaderChunk[ 'displacementmap_pars_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  13583. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  13584. THREE.ShaderChunk[ 'emissivemap_fragment'] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n totalEmissiveLight *= emissiveColor.rgb;\n#endif\n";
  13585. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  13586. THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  13587. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  13588. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envColor.xyz = inputToLinear( envColor.xyz );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n";
  13589. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  13590. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#if defined( USE_ENVMAP ) || defined( STANDARD )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( STANDARD )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  13591. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  13592. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\n varying vec3 vReflect;\n uniform float refractionRatio;\n#endif\n";
  13593. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  13594. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n#endif\n";
  13595. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  13596. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n#endif";
  13597. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  13598. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif";
  13599. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  13600. THREE.ShaderChunk[ 'lights_pars'] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n return PI * ambientLightColor;\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n IncidentLight getDirectionalDirectLight( const in DirectionalLight directionalLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n return directLight;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n int shadow;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n IncidentLight getPointDirectLight( const in PointLight pointLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n directLight.color = pointLight.color;\n directLight.color *= calcLightAttenuation( length( lVector ), pointLight.distance, pointLight.decay );\n return directLight;\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float angleCos;\n float exponent;\n int shadow;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n IncidentLight getSpotDirectLight( const in SpotLight spotLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float spotEffect = dot( directLight.direction, spotLight.direction );\n if ( spotEffect > spotLight.angleCos ) {\n float spotEffect = dot( spotLight.direction, directLight.direction );\n spotEffect = saturate( pow( saturate( spotEffect ), spotLight.exponent ) );\n directLight.color = spotLight.color;\n directLight.color *= ( spotEffect * calcLightAttenuation( length( lVector ), spotLight.distance, spotLight.decay ) );\n } else {\n directLight.color = vec3( 0.0 );\n }\n return directLight;\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n return PI * mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( STANDARD )\n vec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n #if defined( TEXTURE_CUBE_LOD_EXT )\n vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n #else\n vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n #endif\n #else\n vec3 envMapColor = vec3( 0.0 );\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return PI * envMapColor.rgb * envMapIntensity;\n }\n float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n float maxMIPLevelScalar = float( maxMIPLevel );\n float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( square( blinnShininessExponent ) + 1.0 );\n return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n }\n vec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n #if defined( TEXTURE_CUBE_LOD_EXT )\n float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( envMap, queryReflectVec );\n #endif\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envMapColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n";
  13601. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  13602. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  13603. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  13604. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry = GeometricContext( mvPosition.xyz, normalize( transformedNormal ), normalize( -mvPosition.xyz ) );\nGeometricContext backGeometry = GeometricContext( geometry.position, -geometry.normal, geometry.viewDir );\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n IncidentLight directLight = getPointDirectLight( pointLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n IncidentLight directLight = getSpotDirectLight( spotLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n IncidentLight directLight = getDirectionalDirectLight( directionalLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n {\n #if NUM_HEMI_LIGHTS > 0\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n #endif\n }\n #endif\n }\n";
  13605. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  13606. THREE.ShaderChunk[ 'lights_phong_fragment'] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n#ifdef METAL\n material.diffuseColor = vec3( 0.0 );\n#endif\n";
  13607. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  13608. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid BlinnPhongMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * PI * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\n#define Material_RE_DirectLight BlinnPhongMaterial_RE_DirectLight\nvoid BlinnPhongMaterial_RE_IndirectDiffuseLight( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define Material_RE_IndirectDiffuseLight BlinnPhongMaterial_RE_IndirectDiffuseLight\n#define Material_LightProbeLOD( material ) (0)\n";
  13609. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  13610. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\n#if NUM_POINT_LIGHTS > 0\n uniform vec3 pointLightPosition[ NUM_POINT_LIGHTS ];\n#endif\n";
  13611. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  13612. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#ifdef USE_ENVMAP\n vWorldPosition = worldPosition.xyz;\n#endif\n";
  13613. // File:src/renderers/shaders/ShaderChunk/lights_standard_fragment.glsl
  13614. THREE.ShaderChunk[ 'lights_standard_fragment'] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = roughnessFactor * 0.5 + 0.5;material.specularColor = mix( vec3( 0.08 ) * reflectivity, diffuseColor.rgb, metalnessFactor );\n";
  13615. // File:src/renderers/shaders/ShaderChunk/lights_standard_pars_fragment.glsl
  13616. THREE.ShaderChunk[ 'lights_standard_pars_fragment'] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n float clearCoatWeight;\n float clearCoatRoughness;\n};\nvoid PhysicalMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * PI * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n \n}\n#define Material_RE_DirectLight PhysicalMaterial_RE_DirectLight\nvoid PhysicalMaterial_RE_DiffuseIndirectLight( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define Material_RE_IndirectDiffuseLight PhysicalMaterial_RE_DiffuseIndirectLight\nvoid PhysicalMaterial_RE_SpecularIndirectLight( const in vec3 radiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectSpecular += radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n}\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_RE_IndirectSpecularLight PhysicalMaterial_RE_SpecularIndirectLight\n";
  13617. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  13618. THREE.ShaderChunk[ 'lights_template'] = "\nGeometricContext geometry = GeometricContext( -vViewPosition, normal, normalize( vViewPosition ) );\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n PointLight pointLight = pointLights[ i ];\n IncidentLight directLight = getPointDirectLight( pointLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( pointLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == pointLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n SpotLight spotLight = spotLights[ i ];\n IncidentLight directLight = getSpotDirectLight( spotLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( spotLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == spotLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n DirectionalLight directionalLight = directionalLights[ i ];\n IncidentLight directLight = getDirectionalDirectLight( directionalLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( directionalLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == directionalLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( Material_RE_IndirectDiffuseLight )\n {\n vec3 indirectDiffuseIrradiance = getAmbientLightIrradiance( ambientLightColor );\n#ifdef USE_LIGHTMAP\n indirectDiffuseIrradiance += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n#if ( NUM_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n indirectDiffuseIrradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( STANDARD )\n indirectDiffuseIrradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n#endif\n Material_RE_IndirectDiffuseLight( indirectDiffuseIrradiance, geometry, material, reflectedLight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( Material_RE_IndirectSpecularLight )\n {\n vec3 indirectSpecularRadiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n Material_RE_IndirectSpecularLight( indirectSpecularRadiance, geometry, material, reflectedLight );\n }\n#endif\n";
  13619. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  13620. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  13621. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  13622. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  13623. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  13624. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n";
  13625. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  13626. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif";
  13627. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  13628. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n";
  13629. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  13630. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor.xyz = inputToLinear( texelColor.xyz );\n diffuseColor *= texelColor;\n#endif\n";
  13631. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  13632. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif";
  13633. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  13634. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n#endif\n";
  13635. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  13636. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  13637. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  13638. THREE.ShaderChunk[ 'metalnessmap_fragment'] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor = texelMetalness.r;\n#endif\n";
  13639. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  13640. THREE.ShaderChunk[ 'metalnessmap_pars_fragment'] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  13641. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  13642. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  13643. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  13644. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif";
  13645. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  13646. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n";
  13647. // File:src/renderers/shaders/ShaderChunk/normal_phong_fragment.glsl
  13648. THREE.ShaderChunk[ 'normal_phong_fragment'] = "#ifndef FLAT_SHADED\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #endif\n#else\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  13649. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  13650. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\n";
  13651. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  13652. THREE.ShaderChunk[ 'project_vertex'] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  13653. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  13654. THREE.ShaderChunk[ 'roughnessmap_fragment'] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  13655. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  13656. THREE.ShaderChunk[ 'roughnessmap_pars_fragment'] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  13657. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  13658. THREE.ShaderChunk[ 'shadowmap_fragment'] = "vec3 shadowMask = vec3( 1.0 );\n#ifdef USE_SHADOWMAP\n float shadows[ NUM_SHADOWS ];\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n float texelSizeY = 1.0 / shadowMapSize[ i ].y;\n float shadow = 0.0;\n#if defined( POINT_LIGHT_SHADOWS )\n bool isPointLight = shadowDarkness[ i ] < 0.0;\n if ( isPointLight ) {\n float realShadowDarkness = abs( shadowDarkness[ i ] );\n vec3 lightToPosition = vShadowCoord[ i ].xyz;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n #if defined( SHADOWMAP_TYPE_PCF )\n const float Dr = 1.25;\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n const float Dr = 2.25;\n #endif\n float os = Dr * 2.0 * texelSizeY;\n const vec3 Gsd = vec3( - 1, 0, 1 );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness * ( 1.0 / 21.0 );\n #else\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness;\n #endif\n } else {\n#endif\n float texelSizeX = 1.0 / shadowMapSize[ i ].x;\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n shadowCoord.z += shadowBias[ i ];\n const float ShadowDelta = 1.0 / 9.0;\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.25 * xPixelOffset;\n float dy0 = - 1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n float fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n shadow *= shadowDarkness[ i ];\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n shadowCoord.z += shadowBias[ i ];\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.0 * xPixelOffset;\n float dy0 = - 1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n mat3 shadowKernel;\n mat3 depthKernel;\n depthKernel[ 0 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[ 0 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[ 0 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[ 1 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[ 1 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[ 1 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[ 2 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[ 2 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[ 2 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[ 0 ] = vec3( lessThan( depthKernel[ 0 ], shadowZ ) );\n shadowKernel[ 0 ] *= vec3( 0.25 );\n shadowKernel[ 1 ] = vec3( lessThan( depthKernel[ 1 ], shadowZ ) );\n shadowKernel[ 1 ] *= vec3( 0.25 );\n shadowKernel[ 2 ] = vec3( lessThan( depthKernel[ 2 ], shadowZ ) );\n shadowKernel[ 2 ] *= vec3( 0.25 );\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[ i ].xy );\n shadowKernel[ 0 ] = mix( shadowKernel[ 1 ], shadowKernel[ 0 ], fractionalCoord.x );\n shadowKernel[ 1 ] = mix( shadowKernel[ 2 ], shadowKernel[ 1 ], fractionalCoord.x );\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[ 0 ][ 1 ], shadowKernel[ 0 ][ 0 ], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[ 0 ][ 2 ], shadowKernel[ 0 ][ 1 ], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[ 1 ][ 1 ], shadowKernel[ 1 ][ 0 ], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[ 1 ][ 2 ], shadowKernel[ 1 ][ 1 ], fractionalCoord.y );\n shadow = dot( shadowValues, vec4( 1.0 ) ) * shadowDarkness[ i ];\n #else\n shadowCoord.z += shadowBias[ i ];\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n if ( fDepth < shadowCoord.z )\n shadow = shadowDarkness[ i ];\n #endif\n }\n#ifdef SHADOWMAP_DEBUG\n if ( inFrustum ) {\n if ( i == 0 ) {\n outgoingLight *= vec3( 1.0, 0.5, 0.0 );\n } else if ( i == 1 ) {\n outgoingLight *= vec3( 0.0, 1.0, 0.8 );\n } else {\n outgoingLight *= vec3( 0.0, 0.5, 1.0 );\n }\n }\n#endif\n#if defined( POINT_LIGHT_SHADOWS )\n }\n#endif\n shadowMask = shadowMask * vec3( 1.0 - shadow );\n shadows[ i ] = 1.0 - shadow;\n }\n#endif\n";
  13659. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  13660. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n uniform sampler2D shadowMap[ NUM_SHADOWS ];\n uniform vec2 shadowMapSize[ NUM_SHADOWS ];\n uniform float shadowDarkness[ NUM_SHADOWS ];\n uniform float shadowBias[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\n float unpackDepth( const in vec4 rgba_depth ) {\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n }\n #if defined(POINT_LIGHT_SHADOWS)\n void adjustShadowValue1K( const float testDepth, const vec4 textureData, const float bias, inout float shadowValue ) {\n const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n if ( testDepth >= dot( textureData, bitSh ) * 1000.0 + bias )\n shadowValue += 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n #endif\n#endif\n";
  13661. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  13662. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n uniform float shadowDarkness[ NUM_SHADOWS ];\n uniform mat4 shadowMatrix[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\n#endif";
  13663. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  13664. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n }\n#endif";
  13665. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  13666. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  13667. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  13668. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n";
  13669. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  13670. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n#endif\n";
  13671. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  13672. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  13673. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  13674. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif";
  13675. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  13676. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  13677. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  13678. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  13679. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  13680. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  13681. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  13682. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  13683. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  13684. THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n#endif";
  13685. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  13686. THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n";
  13687. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  13688. THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  13689. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  13690. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( STANDARD ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n";
  13691. // File:src/renderers/shaders/UniformsUtils.js
  13692. /**
  13693. * Uniform Utilities
  13694. */
  13695. THREE.UniformsUtils = {
  13696. merge: function ( uniforms ) {
  13697. var merged = {};
  13698. for ( var u = 0; u < uniforms.length; u ++ ) {
  13699. var tmp = this.clone( uniforms[ u ] );
  13700. for ( var p in tmp ) {
  13701. merged[ p ] = tmp[ p ];
  13702. }
  13703. }
  13704. return merged;
  13705. },
  13706. clone: function ( uniforms_src ) {
  13707. var uniforms_dst = {};
  13708. for ( var u in uniforms_src ) {
  13709. uniforms_dst[ u ] = {};
  13710. for ( var p in uniforms_src[ u ] ) {
  13711. var parameter_src = uniforms_src[ u ][ p ];
  13712. if ( parameter_src instanceof THREE.Color ||
  13713. parameter_src instanceof THREE.Vector2 ||
  13714. parameter_src instanceof THREE.Vector3 ||
  13715. parameter_src instanceof THREE.Vector4 ||
  13716. parameter_src instanceof THREE.Matrix3 ||
  13717. parameter_src instanceof THREE.Matrix4 ||
  13718. parameter_src instanceof THREE.Texture ) {
  13719. uniforms_dst[ u ][ p ] = parameter_src.clone();
  13720. } else if ( Array.isArray( parameter_src ) ) {
  13721. uniforms_dst[ u ][ p ] = parameter_src.slice();
  13722. } else {
  13723. uniforms_dst[ u ][ p ] = parameter_src;
  13724. }
  13725. }
  13726. }
  13727. return uniforms_dst;
  13728. }
  13729. };
  13730. // File:src/renderers/shaders/UniformsLib.js
  13731. /**
  13732. * Uniforms library for shared webgl shaders
  13733. */
  13734. THREE.UniformsLib = {
  13735. common: {
  13736. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13737. "opacity" : { type: "f", value: 1.0 },
  13738. "map" : { type: "t", value: null },
  13739. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13740. "specularMap" : { type: "t", value: null },
  13741. "alphaMap" : { type: "t", value: null },
  13742. "envMap" : { type: "t", value: null },
  13743. "flipEnvMap" : { type: "f", value: - 1 },
  13744. "reflectivity" : { type: "f", value: 1.0 },
  13745. "refractionRatio" : { type: "f", value: 0.98 }
  13746. },
  13747. aomap: {
  13748. "aoMap" : { type: "t", value: null },
  13749. "aoMapIntensity" : { type: "f", value: 1 },
  13750. },
  13751. lightmap: {
  13752. "lightMap" : { type: "t", value: null },
  13753. "lightMapIntensity" : { type: "f", value: 1 },
  13754. },
  13755. emissivemap: {
  13756. "emissiveMap" : { type: "t", value: null },
  13757. },
  13758. bumpmap: {
  13759. "bumpMap" : { type: "t", value: null },
  13760. "bumpScale" : { type: "f", value: 1 }
  13761. },
  13762. normalmap: {
  13763. "normalMap" : { type: "t", value: null },
  13764. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  13765. },
  13766. displacementmap: {
  13767. "displacementMap" : { type: "t", value: null },
  13768. "displacementScale" : { type: "f", value: 1 },
  13769. "displacementBias" : { type: "f", value: 0 }
  13770. },
  13771. roughnessmap: {
  13772. "roughnessMap" : { type: "t", value: null }
  13773. },
  13774. reflectivitymap: {
  13775. "reflectivityMap" : { type: "t", value: null }
  13776. },
  13777. metalnessmap: {
  13778. "metalnessMap" : { type: "t", value: null }
  13779. },
  13780. fog : {
  13781. "fogDensity" : { type: "f", value: 0.00025 },
  13782. "fogNear" : { type: "f", value: 1 },
  13783. "fogFar" : { type: "f", value: 2000 },
  13784. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13785. },
  13786. lights: {
  13787. "ambientLightColor" : { type: "fv", value: [] },
  13788. "directionalLights" : { type: "sa", value: [], properties: {
  13789. "direction": { type: "v3" },
  13790. "color": { type: "c" },
  13791. "shadow": { type: "i" }
  13792. } },
  13793. "hemisphereLights" : { type: "sa", value: [], properties: {
  13794. "direction": { type: "v3" },
  13795. "skyColor": { type: "c" },
  13796. "groundColor": { type: "c" }
  13797. } },
  13798. "pointLights" : { type: "sa", value: [], properties: {
  13799. "color": { type: "c" },
  13800. "position": { type: "v3" },
  13801. "decay": { type: "f" },
  13802. "distance": { type: "f" },
  13803. "shadow": { type: "i" }
  13804. } },
  13805. "spotLights" : { type: "sa", value: [], properties: {
  13806. "color": { type: "c" },
  13807. "position": { type: "v3" },
  13808. "direction": { type: "v3" },
  13809. "distance": { type: "f" },
  13810. "angleCos": { type: "f" },
  13811. "exponent": { type: "f" },
  13812. "decay": { type: "f" },
  13813. "shadow": { type: "i" }
  13814. } }
  13815. },
  13816. points: {
  13817. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13818. "opacity" : { type: "f", value: 1.0 },
  13819. "size" : { type: "f", value: 1.0 },
  13820. "scale" : { type: "f", value: 1.0 },
  13821. "map" : { type: "t", value: null },
  13822. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13823. "fogDensity" : { type: "f", value: 0.00025 },
  13824. "fogNear" : { type: "f", value: 1 },
  13825. "fogFar" : { type: "f", value: 2000 },
  13826. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13827. },
  13828. shadowmap: {
  13829. "shadowMap": { type: "tv", value: [] },
  13830. "shadowMapSize": { type: "v2v", value: [] },
  13831. "shadowBias" : { type: "fv1", value: [] },
  13832. "shadowDarkness": { type: "fv1", value: [] },
  13833. "shadowMatrix" : { type: "m4v", value: [] }
  13834. }
  13835. };
  13836. // File:src/renderers/shaders/ShaderLib.js
  13837. /**
  13838. * Webgl Shader Library for three.js
  13839. *
  13840. * @author alteredq / http://alteredqualia.com/
  13841. * @author mrdoob / http://mrdoob.com/
  13842. * @author mikael emtinger / http://gomo.se/
  13843. */
  13844. THREE.ShaderLib = {
  13845. 'basic': {
  13846. uniforms: THREE.UniformsUtils.merge( [
  13847. THREE.UniformsLib[ "common" ],
  13848. THREE.UniformsLib[ "aomap" ],
  13849. THREE.UniformsLib[ "fog" ],
  13850. THREE.UniformsLib[ "shadowmap" ]
  13851. ] ),
  13852. vertexShader: [
  13853. THREE.ShaderChunk[ "common" ],
  13854. THREE.ShaderChunk[ "uv_pars_vertex" ],
  13855. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  13856. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  13857. THREE.ShaderChunk[ "color_pars_vertex" ],
  13858. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  13859. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  13860. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  13861. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  13862. "void main() {",
  13863. THREE.ShaderChunk[ "uv_vertex" ],
  13864. THREE.ShaderChunk[ "uv2_vertex" ],
  13865. THREE.ShaderChunk[ "color_vertex" ],
  13866. THREE.ShaderChunk[ "skinbase_vertex" ],
  13867. " #ifdef USE_ENVMAP",
  13868. THREE.ShaderChunk[ "beginnormal_vertex" ],
  13869. THREE.ShaderChunk[ "morphnormal_vertex" ],
  13870. THREE.ShaderChunk[ "skinnormal_vertex" ],
  13871. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  13872. " #endif",
  13873. THREE.ShaderChunk[ "begin_vertex" ],
  13874. THREE.ShaderChunk[ "morphtarget_vertex" ],
  13875. THREE.ShaderChunk[ "skinning_vertex" ],
  13876. THREE.ShaderChunk[ "project_vertex" ],
  13877. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  13878. THREE.ShaderChunk[ "worldpos_vertex" ],
  13879. THREE.ShaderChunk[ "envmap_vertex" ],
  13880. THREE.ShaderChunk[ "shadowmap_vertex" ],
  13881. "}"
  13882. ].join( "\n" ),
  13883. fragmentShader: [
  13884. "uniform vec3 diffuse;",
  13885. "uniform float opacity;",
  13886. "#ifndef FLAT_SHADED",
  13887. " varying vec3 vNormal;",
  13888. "#endif",
  13889. THREE.ShaderChunk[ "common" ],
  13890. THREE.ShaderChunk[ "color_pars_fragment" ],
  13891. THREE.ShaderChunk[ "uv_pars_fragment" ],
  13892. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  13893. THREE.ShaderChunk[ "map_pars_fragment" ],
  13894. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  13895. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  13896. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  13897. THREE.ShaderChunk[ "fog_pars_fragment" ],
  13898. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  13899. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  13900. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  13901. "void main() {",
  13902. " vec4 diffuseColor = vec4( diffuse, opacity );",
  13903. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  13904. THREE.ShaderChunk[ "map_fragment" ],
  13905. THREE.ShaderChunk[ "color_fragment" ],
  13906. THREE.ShaderChunk[ "alphamap_fragment" ],
  13907. THREE.ShaderChunk[ "alphatest_fragment" ],
  13908. THREE.ShaderChunk[ "specularmap_fragment" ],
  13909. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), diffuseColor.rgb, vec3( 0.0 ) );",
  13910. THREE.ShaderChunk[ "aomap_fragment" ],
  13911. THREE.ShaderChunk[ "shadowmap_fragment" ],
  13912. "reflectedLight.indirectDiffuse *= shadowMask;",
  13913. "vec3 outgoingLight = reflectedLight.indirectDiffuse;",
  13914. THREE.ShaderChunk[ "envmap_fragment" ],
  13915. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  13916. THREE.ShaderChunk[ "fog_fragment" ],
  13917. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  13918. "}"
  13919. ].join( "\n" )
  13920. },
  13921. 'lambert': {
  13922. uniforms: THREE.UniformsUtils.merge( [
  13923. THREE.UniformsLib[ "common" ],
  13924. THREE.UniformsLib[ "fog" ],
  13925. THREE.UniformsLib[ "lights" ],
  13926. THREE.UniformsLib[ "shadowmap" ],
  13927. {
  13928. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  13929. }
  13930. ] ),
  13931. vertexShader: [
  13932. "#define LAMBERT",
  13933. "varying vec3 vLightFront;",
  13934. "#ifdef DOUBLE_SIDED",
  13935. " varying vec3 vLightBack;",
  13936. "#endif",
  13937. THREE.ShaderChunk[ "common" ],
  13938. THREE.ShaderChunk[ "uv_pars_vertex" ],
  13939. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  13940. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  13941. THREE.ShaderChunk[ "bsdfs" ],
  13942. THREE.ShaderChunk[ "lights_pars" ],
  13943. THREE.ShaderChunk[ "color_pars_vertex" ],
  13944. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  13945. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  13946. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  13947. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  13948. "void main() {",
  13949. THREE.ShaderChunk[ "uv_vertex" ],
  13950. THREE.ShaderChunk[ "uv2_vertex" ],
  13951. THREE.ShaderChunk[ "color_vertex" ],
  13952. THREE.ShaderChunk[ "beginnormal_vertex" ],
  13953. THREE.ShaderChunk[ "morphnormal_vertex" ],
  13954. THREE.ShaderChunk[ "skinbase_vertex" ],
  13955. THREE.ShaderChunk[ "skinnormal_vertex" ],
  13956. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  13957. THREE.ShaderChunk[ "begin_vertex" ],
  13958. THREE.ShaderChunk[ "morphtarget_vertex" ],
  13959. THREE.ShaderChunk[ "skinning_vertex" ],
  13960. THREE.ShaderChunk[ "project_vertex" ],
  13961. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  13962. THREE.ShaderChunk[ "worldpos_vertex" ],
  13963. THREE.ShaderChunk[ "envmap_vertex" ],
  13964. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  13965. THREE.ShaderChunk[ "shadowmap_vertex" ],
  13966. "}"
  13967. ].join( "\n" ),
  13968. fragmentShader: [
  13969. "uniform vec3 diffuse;",
  13970. "uniform vec3 emissive;",
  13971. "uniform float opacity;",
  13972. "uniform vec3 ambientLightColor;",
  13973. "varying vec3 vLightFront;",
  13974. "#ifdef DOUBLE_SIDED",
  13975. " varying vec3 vLightBack;",
  13976. "#endif",
  13977. THREE.ShaderChunk[ "common" ],
  13978. THREE.ShaderChunk[ "color_pars_fragment" ],
  13979. THREE.ShaderChunk[ "uv_pars_fragment" ],
  13980. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  13981. THREE.ShaderChunk[ "map_pars_fragment" ],
  13982. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  13983. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  13984. THREE.ShaderChunk[ "fog_pars_fragment" ],
  13985. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  13986. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  13987. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  13988. "void main() {",
  13989. " vec3 outgoingLight = vec3( 0.0 );",
  13990. " vec4 diffuseColor = vec4( diffuse, opacity );",
  13991. " vec3 totalAmbientLight = PI * ambientLightColor;",
  13992. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  13993. THREE.ShaderChunk[ "map_fragment" ],
  13994. THREE.ShaderChunk[ "color_fragment" ],
  13995. THREE.ShaderChunk[ "alphamap_fragment" ],
  13996. THREE.ShaderChunk[ "alphatest_fragment" ],
  13997. THREE.ShaderChunk[ "specularmap_fragment" ],
  13998. THREE.ShaderChunk[ "shadowmap_fragment" ],
  13999. " #ifdef DOUBLE_SIDED",
  14000. " if ( gl_FrontFacing )",
  14001. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14002. " else",
  14003. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightBack * shadowMask + totalAmbientLight ) + emissive;",
  14004. " #else",
  14005. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14006. " #endif",
  14007. THREE.ShaderChunk[ "envmap_fragment" ],
  14008. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14009. THREE.ShaderChunk[ "fog_fragment" ],
  14010. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14011. "}"
  14012. ].join( "\n" )
  14013. },
  14014. 'phong': {
  14015. uniforms: THREE.UniformsUtils.merge( [
  14016. THREE.UniformsLib[ "common" ],
  14017. THREE.UniformsLib[ "aomap" ],
  14018. THREE.UniformsLib[ "lightmap" ],
  14019. THREE.UniformsLib[ "emissivemap" ],
  14020. THREE.UniformsLib[ "bumpmap" ],
  14021. THREE.UniformsLib[ "normalmap" ],
  14022. THREE.UniformsLib[ "displacementmap" ],
  14023. THREE.UniformsLib[ "fog" ],
  14024. THREE.UniformsLib[ "lights" ],
  14025. THREE.UniformsLib[ "shadowmap" ],
  14026. {
  14027. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14028. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14029. "shininess": { type: "f", value: 30 }
  14030. }
  14031. ] ),
  14032. vertexShader: [
  14033. "#define PHONG",
  14034. "varying vec3 vViewPosition;",
  14035. "#ifndef FLAT_SHADED",
  14036. " varying vec3 vNormal;",
  14037. "#endif",
  14038. THREE.ShaderChunk[ "common" ],
  14039. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14040. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14041. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14042. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14043. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  14044. THREE.ShaderChunk[ "color_pars_vertex" ],
  14045. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14046. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14047. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14048. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14049. "void main() {",
  14050. THREE.ShaderChunk[ "uv_vertex" ],
  14051. THREE.ShaderChunk[ "uv2_vertex" ],
  14052. THREE.ShaderChunk[ "color_vertex" ],
  14053. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14054. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14055. THREE.ShaderChunk[ "skinbase_vertex" ],
  14056. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14057. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14058. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14059. " vNormal = normalize( transformedNormal );",
  14060. "#endif",
  14061. THREE.ShaderChunk[ "begin_vertex" ],
  14062. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14063. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14064. THREE.ShaderChunk[ "skinning_vertex" ],
  14065. THREE.ShaderChunk[ "project_vertex" ],
  14066. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14067. " vViewPosition = - mvPosition.xyz;",
  14068. THREE.ShaderChunk[ "worldpos_vertex" ],
  14069. THREE.ShaderChunk[ "envmap_vertex" ],
  14070. THREE.ShaderChunk[ "lights_phong_vertex" ],
  14071. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14072. "}"
  14073. ].join( "\n" ),
  14074. fragmentShader: [
  14075. "#define PHONG",
  14076. "uniform vec3 diffuse;",
  14077. "uniform vec3 emissive;",
  14078. "uniform vec3 specular;",
  14079. "uniform float shininess;",
  14080. "uniform float opacity;",
  14081. THREE.ShaderChunk[ "common" ],
  14082. THREE.ShaderChunk[ "color_pars_fragment" ],
  14083. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14084. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14085. THREE.ShaderChunk[ "map_pars_fragment" ],
  14086. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14087. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14088. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14089. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14090. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14091. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14092. THREE.ShaderChunk[ "bsdfs" ],
  14093. THREE.ShaderChunk[ "lights_pars" ],
  14094. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  14095. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14096. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14097. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14098. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14099. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14100. "void main() {",
  14101. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14102. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14103. " vec3 totalEmissiveLight = emissive;",
  14104. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14105. THREE.ShaderChunk[ "map_fragment" ],
  14106. THREE.ShaderChunk[ "color_fragment" ],
  14107. THREE.ShaderChunk[ "alphamap_fragment" ],
  14108. THREE.ShaderChunk[ "alphatest_fragment" ],
  14109. THREE.ShaderChunk[ "specularmap_fragment" ],
  14110. THREE.ShaderChunk[ "normal_phong_fragment" ],
  14111. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14112. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14113. // accumulation
  14114. THREE.ShaderChunk[ "lights_phong_fragment" ],
  14115. THREE.ShaderChunk[ "lights_template" ],
  14116. THREE.ShaderChunk[ "lightmap_fragment" ],
  14117. // modulation
  14118. THREE.ShaderChunk[ "aomap_fragment" ],
  14119. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14120. THREE.ShaderChunk[ "envmap_fragment" ],
  14121. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14122. THREE.ShaderChunk[ "fog_fragment" ],
  14123. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14124. "}"
  14125. ].join( "\n" )
  14126. },
  14127. 'standard': {
  14128. uniforms: THREE.UniformsUtils.merge( [
  14129. THREE.UniformsLib[ "common" ],
  14130. THREE.UniformsLib[ "aomap" ],
  14131. THREE.UniformsLib[ "lightmap" ],
  14132. THREE.UniformsLib[ "emissivemap" ],
  14133. THREE.UniformsLib[ "bumpmap" ],
  14134. THREE.UniformsLib[ "normalmap" ],
  14135. THREE.UniformsLib[ "displacementmap" ],
  14136. THREE.UniformsLib[ "roughnessmap" ],
  14137. THREE.UniformsLib[ "reflectivitymap" ],
  14138. THREE.UniformsLib[ "metalnessmap" ],
  14139. THREE.UniformsLib[ "fog" ],
  14140. THREE.UniformsLib[ "lights" ],
  14141. THREE.UniformsLib[ "shadowmap" ],
  14142. {
  14143. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14144. "roughness": { type: "f", value: 0.5 },
  14145. "metalness": { type: "f", value: 0 },
  14146. "envMapIntensity" : { type: "f", value: 1 } // temporary
  14147. }
  14148. ] ),
  14149. vertexShader: [
  14150. "#define STANDARD",
  14151. "varying vec3 vViewPosition;",
  14152. "#ifndef FLAT_SHADED",
  14153. " varying vec3 vNormal;",
  14154. "#endif",
  14155. THREE.ShaderChunk[ "common" ],
  14156. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14157. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14158. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14159. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14160. THREE.ShaderChunk[ "lights_phong_pars_vertex" ], // use phong chunk for now
  14161. THREE.ShaderChunk[ "color_pars_vertex" ],
  14162. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14163. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14164. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14165. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14166. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14167. "void main() {", // STANDARD
  14168. THREE.ShaderChunk[ "uv_vertex" ],
  14169. THREE.ShaderChunk[ "uv2_vertex" ],
  14170. THREE.ShaderChunk[ "color_vertex" ],
  14171. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14172. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14173. THREE.ShaderChunk[ "skinbase_vertex" ],
  14174. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14175. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14176. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14177. " vNormal = normalize( transformedNormal );",
  14178. "#endif",
  14179. THREE.ShaderChunk[ "begin_vertex" ],
  14180. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14181. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14182. THREE.ShaderChunk[ "skinning_vertex" ],
  14183. THREE.ShaderChunk[ "project_vertex" ],
  14184. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14185. " vViewPosition = - mvPosition.xyz;",
  14186. THREE.ShaderChunk[ "worldpos_vertex" ],
  14187. THREE.ShaderChunk[ "envmap_vertex" ],
  14188. THREE.ShaderChunk[ "lights_phong_vertex" ], // use phong chunk for now
  14189. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14190. "}"
  14191. ].join( "\n" ),
  14192. fragmentShader: [
  14193. "#define STANDARD",
  14194. "uniform vec3 diffuse;",
  14195. "uniform vec3 emissive;",
  14196. "uniform float roughness;",
  14197. "uniform float metalness;",
  14198. "uniform float opacity;",
  14199. "uniform float envMapIntensity;", // temporary
  14200. "varying vec3 vViewPosition;",
  14201. "#ifndef FLAT_SHADED",
  14202. " varying vec3 vNormal;",
  14203. "#endif",
  14204. THREE.ShaderChunk[ "common" ],
  14205. THREE.ShaderChunk[ "color_pars_fragment" ],
  14206. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14207. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14208. THREE.ShaderChunk[ "map_pars_fragment" ],
  14209. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14210. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14211. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14212. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14213. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14214. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14215. THREE.ShaderChunk[ "bsdfs" ],
  14216. THREE.ShaderChunk[ "lights_pars" ],
  14217. THREE.ShaderChunk[ "lights_standard_pars_fragment" ],
  14218. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14219. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14220. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14221. THREE.ShaderChunk[ "roughnessmap_pars_fragment" ],
  14222. //THREE.ShaderChunk[ "reflectivitymap_pars_fragment" ],
  14223. THREE.ShaderChunk[ "metalnessmap_pars_fragment" ],
  14224. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14225. "void main() {",
  14226. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14227. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14228. " vec3 totalEmissiveLight = emissive;",
  14229. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14230. THREE.ShaderChunk[ "map_fragment" ],
  14231. THREE.ShaderChunk[ "color_fragment" ],
  14232. THREE.ShaderChunk[ "alphamap_fragment" ],
  14233. THREE.ShaderChunk[ "alphatest_fragment" ],
  14234. THREE.ShaderChunk[ "specularmap_fragment" ],
  14235. THREE.ShaderChunk[ "roughnessmap_fragment" ],
  14236. //THREE.ShaderChunk[ "reflectivitymap_fragment" ],
  14237. THREE.ShaderChunk[ "metalnessmap_fragment" ],
  14238. THREE.ShaderChunk[ "normal_phong_fragment" ], // use phong chunk for now
  14239. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14240. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14241. // accumulation
  14242. THREE.ShaderChunk[ "lights_standard_fragment" ],
  14243. THREE.ShaderChunk[ "lights_template" ],
  14244. THREE.ShaderChunk[ "lightmap_fragment" ],
  14245. // modulation
  14246. THREE.ShaderChunk[ "aomap_fragment" ],
  14247. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14248. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14249. THREE.ShaderChunk[ "fog_fragment" ],
  14250. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14251. "}"
  14252. ].join( "\n" )
  14253. },
  14254. 'points': {
  14255. uniforms: THREE.UniformsUtils.merge( [
  14256. THREE.UniformsLib[ "points" ],
  14257. THREE.UniformsLib[ "shadowmap" ]
  14258. ] ),
  14259. vertexShader: [
  14260. "uniform float size;",
  14261. "uniform float scale;",
  14262. THREE.ShaderChunk[ "common" ],
  14263. THREE.ShaderChunk[ "color_pars_vertex" ],
  14264. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14265. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14266. "void main() {",
  14267. THREE.ShaderChunk[ "color_vertex" ],
  14268. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14269. " #ifdef USE_SIZEATTENUATION",
  14270. " gl_PointSize = size * ( scale / -mvPosition.z );",
  14271. " #else",
  14272. " gl_PointSize = size;",
  14273. " #endif",
  14274. " gl_Position = projectionMatrix * mvPosition;",
  14275. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14276. THREE.ShaderChunk[ "worldpos_vertex" ],
  14277. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14278. "}"
  14279. ].join( "\n" ),
  14280. fragmentShader: [
  14281. "uniform vec3 psColor;",
  14282. "uniform float opacity;",
  14283. THREE.ShaderChunk[ "common" ],
  14284. THREE.ShaderChunk[ "color_pars_fragment" ],
  14285. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  14286. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14287. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14288. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14289. "void main() {",
  14290. " vec3 outgoingLight = vec3( 0.0 );",
  14291. " vec4 diffuseColor = vec4( psColor, opacity );",
  14292. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14293. THREE.ShaderChunk[ "map_particle_fragment" ],
  14294. THREE.ShaderChunk[ "color_fragment" ],
  14295. THREE.ShaderChunk[ "alphatest_fragment" ],
  14296. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14297. " outgoingLight = diffuseColor.rgb * shadowMask;",
  14298. THREE.ShaderChunk[ "fog_fragment" ],
  14299. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14300. "}"
  14301. ].join( "\n" )
  14302. },
  14303. 'dashed': {
  14304. uniforms: THREE.UniformsUtils.merge( [
  14305. THREE.UniformsLib[ "common" ],
  14306. THREE.UniformsLib[ "fog" ],
  14307. {
  14308. "scale" : { type: "f", value: 1 },
  14309. "dashSize" : { type: "f", value: 1 },
  14310. "totalSize": { type: "f", value: 2 }
  14311. }
  14312. ] ),
  14313. vertexShader: [
  14314. "uniform float scale;",
  14315. "attribute float lineDistance;",
  14316. "varying float vLineDistance;",
  14317. THREE.ShaderChunk[ "common" ],
  14318. THREE.ShaderChunk[ "color_pars_vertex" ],
  14319. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14320. "void main() {",
  14321. THREE.ShaderChunk[ "color_vertex" ],
  14322. " vLineDistance = scale * lineDistance;",
  14323. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14324. " gl_Position = projectionMatrix * mvPosition;",
  14325. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14326. "}"
  14327. ].join( "\n" ),
  14328. fragmentShader: [
  14329. "uniform vec3 diffuse;",
  14330. "uniform float opacity;",
  14331. "uniform float dashSize;",
  14332. "uniform float totalSize;",
  14333. "varying float vLineDistance;",
  14334. THREE.ShaderChunk[ "common" ],
  14335. THREE.ShaderChunk[ "color_pars_fragment" ],
  14336. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14337. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14338. "void main() {",
  14339. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  14340. " discard;",
  14341. " }",
  14342. " vec3 outgoingLight = vec3( 0.0 );",
  14343. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14344. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14345. THREE.ShaderChunk[ "color_fragment" ],
  14346. " outgoingLight = diffuseColor.rgb;", // simple shader
  14347. THREE.ShaderChunk[ "fog_fragment" ],
  14348. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14349. "}"
  14350. ].join( "\n" )
  14351. },
  14352. 'depth': {
  14353. uniforms: {
  14354. "mNear": { type: "f", value: 1.0 },
  14355. "mFar" : { type: "f", value: 2000.0 },
  14356. "opacity" : { type: "f", value: 1.0 }
  14357. },
  14358. vertexShader: [
  14359. THREE.ShaderChunk[ "common" ],
  14360. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14361. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14362. "void main() {",
  14363. THREE.ShaderChunk[ "begin_vertex" ],
  14364. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14365. THREE.ShaderChunk[ "project_vertex" ],
  14366. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14367. "}"
  14368. ].join( "\n" ),
  14369. fragmentShader: [
  14370. "uniform float mNear;",
  14371. "uniform float mFar;",
  14372. "uniform float opacity;",
  14373. THREE.ShaderChunk[ "common" ],
  14374. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14375. "void main() {",
  14376. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14377. " #ifdef USE_LOGDEPTHBUF_EXT",
  14378. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  14379. " #else",
  14380. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  14381. " #endif",
  14382. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  14383. " gl_FragColor = vec4( vec3( color ), opacity );",
  14384. "}"
  14385. ].join( "\n" )
  14386. },
  14387. 'normal': {
  14388. uniforms: {
  14389. "opacity" : { type: "f", value: 1.0 }
  14390. },
  14391. vertexShader: [
  14392. "varying vec3 vNormal;",
  14393. THREE.ShaderChunk[ "common" ],
  14394. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14395. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14396. "void main() {",
  14397. " vNormal = normalize( normalMatrix * normal );",
  14398. THREE.ShaderChunk[ "begin_vertex" ],
  14399. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14400. THREE.ShaderChunk[ "project_vertex" ],
  14401. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14402. "}"
  14403. ].join( "\n" ),
  14404. fragmentShader: [
  14405. "uniform float opacity;",
  14406. "varying vec3 vNormal;",
  14407. THREE.ShaderChunk[ "common" ],
  14408. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14409. "void main() {",
  14410. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  14411. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14412. "}"
  14413. ].join( "\n" )
  14414. },
  14415. /* -------------------------------------------------------------------------
  14416. // Cube map shader
  14417. ------------------------------------------------------------------------- */
  14418. 'cube': {
  14419. uniforms: { "tCube": { type: "t", value: null },
  14420. "tFlip": { type: "f", value: - 1 } },
  14421. vertexShader: [
  14422. "varying vec3 vWorldPosition;",
  14423. THREE.ShaderChunk[ "common" ],
  14424. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14425. "void main() {",
  14426. " vWorldPosition = transformDirection( position, modelMatrix );",
  14427. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14428. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14429. "}"
  14430. ].join( "\n" ),
  14431. fragmentShader: [
  14432. "uniform samplerCube tCube;",
  14433. "uniform float tFlip;",
  14434. "varying vec3 vWorldPosition;",
  14435. THREE.ShaderChunk[ "common" ],
  14436. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14437. "void main() {",
  14438. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14439. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14440. "}"
  14441. ].join( "\n" )
  14442. },
  14443. /* -------------------------------------------------------------------------
  14444. // Cube map shader
  14445. ------------------------------------------------------------------------- */
  14446. 'equirect': {
  14447. uniforms: { "tEquirect": { type: "t", value: null },
  14448. "tFlip": { type: "f", value: - 1 } },
  14449. vertexShader: [
  14450. "varying vec3 vWorldPosition;",
  14451. THREE.ShaderChunk[ "common" ],
  14452. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14453. "void main() {",
  14454. " vWorldPosition = transformDirection( position, modelMatrix );",
  14455. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14456. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14457. "}"
  14458. ].join( "\n" ),
  14459. fragmentShader: [
  14460. "uniform sampler2D tEquirect;",
  14461. "uniform float tFlip;",
  14462. "varying vec3 vWorldPosition;",
  14463. THREE.ShaderChunk[ "common" ],
  14464. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14465. "void main() {",
  14466. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14467. "vec3 direction = normalize( vWorldPosition );",
  14468. "vec2 sampleUV;",
  14469. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  14470. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  14471. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  14472. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14473. "}"
  14474. ].join( "\n" )
  14475. },
  14476. /* Depth encoding into RGBA texture
  14477. *
  14478. * based on SpiderGL shadow map example
  14479. * http://spidergl.org/example.php?id=6
  14480. *
  14481. * originally from
  14482. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  14483. *
  14484. * see also
  14485. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  14486. */
  14487. 'depthRGBA': {
  14488. uniforms: {},
  14489. vertexShader: [
  14490. THREE.ShaderChunk[ "common" ],
  14491. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14492. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14493. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14494. "void main() {",
  14495. THREE.ShaderChunk[ "skinbase_vertex" ],
  14496. THREE.ShaderChunk[ "begin_vertex" ],
  14497. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14498. THREE.ShaderChunk[ "skinning_vertex" ],
  14499. THREE.ShaderChunk[ "project_vertex" ],
  14500. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14501. "}"
  14502. ].join( "\n" ),
  14503. fragmentShader: [
  14504. THREE.ShaderChunk[ "common" ],
  14505. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14506. "vec4 pack_depth( const in float depth ) {",
  14507. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14508. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14509. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  14510. " res -= res.xxyz * bit_mask;",
  14511. " return res;",
  14512. "}",
  14513. "void main() {",
  14514. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14515. " #ifdef USE_LOGDEPTHBUF_EXT",
  14516. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  14517. " #else",
  14518. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  14519. " #endif",
  14520. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  14521. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  14522. //"gl_FragData[ 0 ] = pack_depth( z );",
  14523. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  14524. "}"
  14525. ].join( "\n" )
  14526. },
  14527. 'distanceRGBA': {
  14528. uniforms: {
  14529. "lightPos": { type: "v3", value: new THREE.Vector3( 0, 0, 0 ) }
  14530. },
  14531. vertexShader: [
  14532. "varying vec4 vWorldPosition;",
  14533. THREE.ShaderChunk[ "common" ],
  14534. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14535. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14536. "void main() {",
  14537. THREE.ShaderChunk[ "skinbase_vertex" ],
  14538. THREE.ShaderChunk[ "begin_vertex" ],
  14539. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14540. THREE.ShaderChunk[ "skinning_vertex" ],
  14541. THREE.ShaderChunk[ "project_vertex" ],
  14542. THREE.ShaderChunk[ "worldpos_vertex" ],
  14543. "vWorldPosition = worldPosition;",
  14544. "}"
  14545. ].join( "\n" ),
  14546. fragmentShader: [
  14547. "uniform vec3 lightPos;",
  14548. "varying vec4 vWorldPosition;",
  14549. THREE.ShaderChunk[ "common" ],
  14550. "vec4 pack1K ( float depth ) {",
  14551. " depth /= 1000.0;",
  14552. " const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14553. " const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14554. " vec4 res = fract( depth * bitSh );",
  14555. " res -= res.xxyz * bitMsk;",
  14556. " return res; ",
  14557. "}",
  14558. "float unpack1K ( vec4 color ) {",
  14559. " const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  14560. " return dot( color, bitSh ) * 1000.0;",
  14561. "}",
  14562. "void main () {",
  14563. " gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );",
  14564. "}"
  14565. ].join( "\n" )
  14566. }
  14567. };
  14568. // File:src/renderers/WebGLRenderer.js
  14569. /**
  14570. * @author supereggbert / http://www.paulbrunt.co.uk/
  14571. * @author mrdoob / http://mrdoob.com/
  14572. * @author alteredq / http://alteredqualia.com/
  14573. * @author szimek / https://github.com/szimek/
  14574. */
  14575. THREE.WebGLRenderer = function ( parameters ) {
  14576. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14577. parameters = parameters || {};
  14578. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14579. _context = parameters.context !== undefined ? parameters.context : null,
  14580. _width = _canvas.width,
  14581. _height = _canvas.height,
  14582. pixelRatio = 1,
  14583. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14584. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14585. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14586. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14587. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14588. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14589. _clearColor = new THREE.Color( 0x000000 ),
  14590. _clearAlpha = 0;
  14591. var lights = [];
  14592. var opaqueObjects = [];
  14593. var opaqueObjectsLastIndex = - 1;
  14594. var transparentObjects = [];
  14595. var transparentObjectsLastIndex = - 1;
  14596. var morphInfluences = new Float32Array( 8 );
  14597. var sprites = [];
  14598. var lensFlares = [];
  14599. // public properties
  14600. this.domElement = _canvas;
  14601. this.context = null;
  14602. // clearing
  14603. this.autoClear = true;
  14604. this.autoClearColor = true;
  14605. this.autoClearDepth = true;
  14606. this.autoClearStencil = true;
  14607. // scene graph
  14608. this.sortObjects = true;
  14609. // physically based shading
  14610. this.gammaFactor = 2.0; // for backwards compatibility
  14611. this.gammaInput = false;
  14612. this.gammaOutput = false;
  14613. // morphs
  14614. this.maxMorphTargets = 8;
  14615. this.maxMorphNormals = 4;
  14616. // flags
  14617. this.autoScaleCubemaps = true;
  14618. // internal properties
  14619. var _this = this,
  14620. // internal state cache
  14621. _currentProgram = null,
  14622. _currentFramebuffer = null,
  14623. _currentMaterialId = - 1,
  14624. _currentGeometryProgram = '',
  14625. _currentCamera = null,
  14626. _usedTextureUnits = 0,
  14627. _viewportX = 0,
  14628. _viewportY = 0,
  14629. _viewportWidth = _canvas.width,
  14630. _viewportHeight = _canvas.height,
  14631. _currentWidth = 0,
  14632. _currentHeight = 0,
  14633. // frustum
  14634. _frustum = new THREE.Frustum(),
  14635. // camera matrices cache
  14636. _projScreenMatrix = new THREE.Matrix4(),
  14637. _vector3 = new THREE.Vector3(),
  14638. // light arrays cache
  14639. _lights = {
  14640. hash: '',
  14641. ambient: [ 0, 0, 0 ],
  14642. directional: [],
  14643. point: [],
  14644. spot: [],
  14645. hemi: [],
  14646. shadows: [],
  14647. shadowsPointLight: 0
  14648. },
  14649. // info
  14650. _infoMemory = {
  14651. geometries: 0,
  14652. textures: 0
  14653. },
  14654. _infoRender = {
  14655. calls: 0,
  14656. vertices: 0,
  14657. faces: 0,
  14658. points: 0
  14659. };
  14660. this.info = {
  14661. render: _infoRender,
  14662. memory: _infoMemory,
  14663. programs: null
  14664. };
  14665. // initialize
  14666. var _gl;
  14667. try {
  14668. var attributes = {
  14669. alpha: _alpha,
  14670. depth: _depth,
  14671. stencil: _stencil,
  14672. antialias: _antialias,
  14673. premultipliedAlpha: _premultipliedAlpha,
  14674. preserveDrawingBuffer: _preserveDrawingBuffer
  14675. };
  14676. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14677. if ( _gl === null ) {
  14678. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14679. throw 'Error creating WebGL context with your selected attributes.';
  14680. } else {
  14681. throw 'Error creating WebGL context.';
  14682. }
  14683. }
  14684. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14685. } catch ( error ) {
  14686. console.error( 'THREE.WebGLRenderer: ' + error );
  14687. }
  14688. var extensions = new THREE.WebGLExtensions( _gl );
  14689. extensions.get( 'OES_texture_float' );
  14690. extensions.get( 'OES_texture_float_linear' );
  14691. extensions.get( 'OES_texture_half_float' );
  14692. extensions.get( 'OES_texture_half_float_linear' );
  14693. extensions.get( 'OES_standard_derivatives' );
  14694. extensions.get( 'ANGLE_instanced_arrays' );
  14695. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14696. THREE.BufferGeometry.MaxIndex = 4294967296;
  14697. }
  14698. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14699. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14700. var properties = new THREE.WebGLProperties();
  14701. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14702. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14703. this.info.programs = programCache.programs;
  14704. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14705. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14706. //
  14707. function glClearColor( r, g, b, a ) {
  14708. if ( _premultipliedAlpha === true ) {
  14709. r *= a; g *= a; b *= a;
  14710. }
  14711. _gl.clearColor( r, g, b, a );
  14712. }
  14713. function setDefaultGLState() {
  14714. state.init();
  14715. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14716. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14717. }
  14718. function resetGLState() {
  14719. _currentProgram = null;
  14720. _currentCamera = null;
  14721. _currentGeometryProgram = '';
  14722. _currentMaterialId = - 1;
  14723. state.reset();
  14724. }
  14725. setDefaultGLState();
  14726. this.context = _gl;
  14727. this.capabilities = capabilities;
  14728. this.extensions = extensions;
  14729. this.state = state;
  14730. // shadow map
  14731. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  14732. this.shadowMap = shadowMap;
  14733. // Plugins
  14734. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14735. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14736. // API
  14737. this.getContext = function () {
  14738. return _gl;
  14739. };
  14740. this.getContextAttributes = function () {
  14741. return _gl.getContextAttributes();
  14742. };
  14743. this.forceContextLoss = function () {
  14744. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14745. };
  14746. this.getMaxAnisotropy = ( function () {
  14747. var value;
  14748. return function getMaxAnisotropy() {
  14749. if ( value !== undefined ) return value;
  14750. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14751. if ( extension !== null ) {
  14752. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14753. } else {
  14754. value = 0;
  14755. }
  14756. return value;
  14757. }
  14758. } )();
  14759. this.getPrecision = function () {
  14760. return capabilities.precision;
  14761. };
  14762. this.getPixelRatio = function () {
  14763. return pixelRatio;
  14764. };
  14765. this.setPixelRatio = function ( value ) {
  14766. if ( value !== undefined ) pixelRatio = value;
  14767. };
  14768. this.getSize = function () {
  14769. return {
  14770. width: _width,
  14771. height: _height
  14772. };
  14773. };
  14774. this.setSize = function ( width, height, updateStyle ) {
  14775. _width = width;
  14776. _height = height;
  14777. _canvas.width = width * pixelRatio;
  14778. _canvas.height = height * pixelRatio;
  14779. if ( updateStyle !== false ) {
  14780. _canvas.style.width = width + 'px';
  14781. _canvas.style.height = height + 'px';
  14782. }
  14783. this.setViewport( 0, 0, width, height );
  14784. };
  14785. this.setViewport = function ( x, y, width, height ) {
  14786. _viewportX = x * pixelRatio;
  14787. _viewportY = y * pixelRatio;
  14788. _viewportWidth = width * pixelRatio;
  14789. _viewportHeight = height * pixelRatio;
  14790. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14791. };
  14792. this.getViewport = function ( dimensions ) {
  14793. dimensions.x = _viewportX / pixelRatio;
  14794. dimensions.y = _viewportY / pixelRatio;
  14795. dimensions.z = _viewportWidth / pixelRatio;
  14796. dimensions.w = _viewportHeight / pixelRatio;
  14797. };
  14798. this.setScissor = function ( x, y, width, height ) {
  14799. _gl.scissor(
  14800. x * pixelRatio,
  14801. y * pixelRatio,
  14802. width * pixelRatio,
  14803. height * pixelRatio
  14804. );
  14805. };
  14806. this.enableScissorTest = function ( boolean ) {
  14807. state.setScissorTest( boolean );
  14808. };
  14809. // Clearing
  14810. this.getClearColor = function () {
  14811. return _clearColor;
  14812. };
  14813. this.setClearColor = function ( color, alpha ) {
  14814. _clearColor.set( color );
  14815. _clearAlpha = alpha !== undefined ? alpha : 1;
  14816. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14817. };
  14818. this.getClearAlpha = function () {
  14819. return _clearAlpha;
  14820. };
  14821. this.setClearAlpha = function ( alpha ) {
  14822. _clearAlpha = alpha;
  14823. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14824. };
  14825. this.clear = function ( color, depth, stencil ) {
  14826. var bits = 0;
  14827. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14828. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14829. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14830. _gl.clear( bits );
  14831. };
  14832. this.clearColor = function () {
  14833. _gl.clear( _gl.COLOR_BUFFER_BIT );
  14834. };
  14835. this.clearDepth = function () {
  14836. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  14837. };
  14838. this.clearStencil = function () {
  14839. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  14840. };
  14841. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14842. this.setRenderTarget( renderTarget );
  14843. this.clear( color, depth, stencil );
  14844. };
  14845. // Reset
  14846. this.resetGLState = resetGLState;
  14847. this.dispose = function() {
  14848. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14849. };
  14850. // Events
  14851. function onContextLost( event ) {
  14852. event.preventDefault();
  14853. resetGLState();
  14854. setDefaultGLState();
  14855. properties.clear();
  14856. };
  14857. function onTextureDispose( event ) {
  14858. var texture = event.target;
  14859. texture.removeEventListener( 'dispose', onTextureDispose );
  14860. deallocateTexture( texture );
  14861. _infoMemory.textures --;
  14862. }
  14863. function onRenderTargetDispose( event ) {
  14864. var renderTarget = event.target;
  14865. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14866. deallocateRenderTarget( renderTarget );
  14867. _infoMemory.textures --;
  14868. }
  14869. function onMaterialDispose( event ) {
  14870. var material = event.target;
  14871. material.removeEventListener( 'dispose', onMaterialDispose );
  14872. deallocateMaterial( material );
  14873. }
  14874. // Buffer deallocation
  14875. function deallocateTexture( texture ) {
  14876. var textureProperties = properties.get( texture );
  14877. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14878. // cube texture
  14879. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14880. } else {
  14881. // 2D texture
  14882. if ( textureProperties.__webglInit === undefined ) return;
  14883. _gl.deleteTexture( textureProperties.__webglTexture );
  14884. }
  14885. // remove all webgl properties
  14886. properties.delete( texture );
  14887. }
  14888. function deallocateRenderTarget( renderTarget ) {
  14889. var renderTargetProperties = properties.get( renderTarget );
  14890. var textureProperties = properties.get( renderTarget.texture );
  14891. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  14892. _gl.deleteTexture( textureProperties.__webglTexture );
  14893. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14894. for ( var i = 0; i < 6; i ++ ) {
  14895. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14896. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
  14897. }
  14898. } else {
  14899. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14900. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
  14901. }
  14902. properties.delete( renderTarget.texture );
  14903. properties.delete( renderTarget );
  14904. }
  14905. function deallocateMaterial( material ) {
  14906. releaseMaterialProgramReference( material );
  14907. properties.delete( material );
  14908. }
  14909. function releaseMaterialProgramReference( material ) {
  14910. var programInfo = properties.get( material ).program;
  14911. material.program = undefined;
  14912. if ( programInfo !== undefined ) {
  14913. programCache.releaseProgram( programInfo );
  14914. }
  14915. }
  14916. // Buffer rendering
  14917. this.renderBufferImmediate = function ( object, program, material ) {
  14918. state.initAttributes();
  14919. var buffers = properties.get( object );
  14920. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14921. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14922. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14923. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14924. var attributes = program.getAttributes();
  14925. if ( object.hasPositions ) {
  14926. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  14927. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  14928. state.enableAttribute( attributes.position );
  14929. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14930. }
  14931. if ( object.hasNormals ) {
  14932. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  14933. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  14934. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  14935. var array = object.normalArray;
  14936. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  14937. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  14938. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  14939. array[ i + 0 ] = nx;
  14940. array[ i + 1 ] = ny;
  14941. array[ i + 2 ] = nz;
  14942. array[ i + 3 ] = nx;
  14943. array[ i + 4 ] = ny;
  14944. array[ i + 5 ] = nz;
  14945. array[ i + 6 ] = nx;
  14946. array[ i + 7 ] = ny;
  14947. array[ i + 8 ] = nz;
  14948. }
  14949. }
  14950. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  14951. state.enableAttribute( attributes.normal );
  14952. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14953. }
  14954. if ( object.hasUvs && material.map ) {
  14955. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  14956. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  14957. state.enableAttribute( attributes.uv );
  14958. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14959. }
  14960. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  14961. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  14962. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  14963. state.enableAttribute( attributes.color );
  14964. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14965. }
  14966. state.disableUnusedAttributes();
  14967. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  14968. object.count = 0;
  14969. };
  14970. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  14971. setMaterial( material );
  14972. var program = setProgram( camera, fog, material, object );
  14973. var updateBuffers = false;
  14974. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  14975. if ( geometryProgram !== _currentGeometryProgram ) {
  14976. _currentGeometryProgram = geometryProgram;
  14977. updateBuffers = true;
  14978. }
  14979. // morph targets
  14980. var morphTargetInfluences = object.morphTargetInfluences;
  14981. if ( morphTargetInfluences !== undefined ) {
  14982. var activeInfluences = [];
  14983. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  14984. var influence = morphTargetInfluences[ i ];
  14985. activeInfluences.push( [ influence, i ] );
  14986. }
  14987. activeInfluences.sort( numericalSort );
  14988. if ( activeInfluences.length > 8 ) {
  14989. activeInfluences.length = 8;
  14990. }
  14991. var morphAttributes = geometry.morphAttributes;
  14992. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  14993. var influence = activeInfluences[ i ];
  14994. morphInfluences[ i ] = influence[ 0 ];
  14995. if ( influence[ 0 ] !== 0 ) {
  14996. var index = influence[ 1 ];
  14997. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  14998. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  14999. } else {
  15000. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  15001. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  15002. }
  15003. }
  15004. var uniforms = program.getUniforms();
  15005. if ( uniforms.morphTargetInfluences !== null ) {
  15006. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  15007. }
  15008. updateBuffers = true;
  15009. }
  15010. //
  15011. var index = geometry.index;
  15012. var position = geometry.attributes.position;
  15013. if ( material.wireframe === true ) {
  15014. index = objects.getWireframeAttribute( geometry );
  15015. }
  15016. var renderer;
  15017. if ( index !== null ) {
  15018. renderer = indexedBufferRenderer;
  15019. renderer.setIndex( index );
  15020. } else {
  15021. renderer = bufferRenderer;
  15022. }
  15023. if ( updateBuffers ) {
  15024. setupVertexAttributes( material, program, geometry );
  15025. if ( index !== null ) {
  15026. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  15027. }
  15028. }
  15029. //
  15030. var dataStart = 0;
  15031. var dataCount = Infinity;
  15032. if ( index !== null ) {
  15033. dataCount = index.count
  15034. } else if ( position !== undefined ) {
  15035. dataCount = position.count;
  15036. }
  15037. var rangeStart = geometry.drawRange.start;
  15038. var rangeCount = geometry.drawRange.count;
  15039. var groupStart = group !== null ? group.start : 0;
  15040. var groupCount = group !== null ? group.count : Infinity;
  15041. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15042. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15043. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15044. //
  15045. if ( object instanceof THREE.Mesh ) {
  15046. if ( material.wireframe === true ) {
  15047. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  15048. renderer.setMode( _gl.LINES );
  15049. } else {
  15050. switch ( object.drawMode ) {
  15051. case THREE.TrianglesDrawMode:
  15052. renderer.setMode( _gl.TRIANGLES );
  15053. break;
  15054. case THREE.TriangleStripDrawMode:
  15055. renderer.setMode( _gl.TRIANGLE_STRIP );
  15056. break;
  15057. case THREE.TriangleFanDrawMode:
  15058. renderer.setMode( _gl.TRIANGLE_FAN );
  15059. break;
  15060. }
  15061. }
  15062. } else if ( object instanceof THREE.Line ) {
  15063. var lineWidth = material.linewidth;
  15064. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15065. state.setLineWidth( lineWidth * pixelRatio );
  15066. if ( object instanceof THREE.LineSegments ) {
  15067. renderer.setMode( _gl.LINES );
  15068. } else {
  15069. renderer.setMode( _gl.LINE_STRIP );
  15070. }
  15071. } else if ( object instanceof THREE.Points ) {
  15072. renderer.setMode( _gl.POINTS );
  15073. }
  15074. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  15075. renderer.renderInstances( geometry, drawStart, drawCount );
  15076. } else {
  15077. renderer.render( drawStart, drawCount );
  15078. }
  15079. };
  15080. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15081. var extension;
  15082. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15083. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15084. if ( extension === null ) {
  15085. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15086. return;
  15087. }
  15088. }
  15089. if ( startIndex === undefined ) startIndex = 0;
  15090. state.initAttributes();
  15091. var geometryAttributes = geometry.attributes;
  15092. var programAttributes = program.getAttributes();
  15093. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15094. for ( var name in programAttributes ) {
  15095. var programAttribute = programAttributes[ name ];
  15096. if ( programAttribute >= 0 ) {
  15097. var geometryAttribute = geometryAttributes[ name ];
  15098. if ( geometryAttribute !== undefined ) {
  15099. var size = geometryAttribute.itemSize;
  15100. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15101. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15102. var data = geometryAttribute.data;
  15103. var stride = data.stride;
  15104. var offset = geometryAttribute.offset;
  15105. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15106. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15107. if ( geometry.maxInstancedCount === undefined ) {
  15108. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15109. }
  15110. } else {
  15111. state.enableAttribute( programAttribute );
  15112. }
  15113. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15114. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15115. } else {
  15116. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15117. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15118. if ( geometry.maxInstancedCount === undefined ) {
  15119. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15120. }
  15121. } else {
  15122. state.enableAttribute( programAttribute );
  15123. }
  15124. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15125. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  15126. }
  15127. } else if ( materialDefaultAttributeValues !== undefined ) {
  15128. var value = materialDefaultAttributeValues[ name ];
  15129. if ( value !== undefined ) {
  15130. switch ( value.length ) {
  15131. case 2:
  15132. _gl.vertexAttrib2fv( programAttribute, value );
  15133. break;
  15134. case 3:
  15135. _gl.vertexAttrib3fv( programAttribute, value );
  15136. break;
  15137. case 4:
  15138. _gl.vertexAttrib4fv( programAttribute, value );
  15139. break;
  15140. default:
  15141. _gl.vertexAttrib1fv( programAttribute, value );
  15142. }
  15143. }
  15144. }
  15145. }
  15146. }
  15147. state.disableUnusedAttributes();
  15148. }
  15149. // Sorting
  15150. function numericalSort ( a, b ) {
  15151. return b[ 0 ] - a[ 0 ];
  15152. }
  15153. function painterSortStable ( a, b ) {
  15154. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15155. return a.object.renderOrder - b.object.renderOrder;
  15156. } else if ( a.material.id !== b.material.id ) {
  15157. return a.material.id - b.material.id;
  15158. } else if ( a.z !== b.z ) {
  15159. return a.z - b.z;
  15160. } else {
  15161. return a.id - b.id;
  15162. }
  15163. }
  15164. function reversePainterSortStable ( a, b ) {
  15165. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15166. return a.object.renderOrder - b.object.renderOrder;
  15167. } if ( a.z !== b.z ) {
  15168. return b.z - a.z;
  15169. } else {
  15170. return a.id - b.id;
  15171. }
  15172. }
  15173. // Rendering
  15174. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15175. if ( camera instanceof THREE.Camera === false ) {
  15176. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15177. return;
  15178. }
  15179. var fog = scene.fog;
  15180. // reset caching for this frame
  15181. _currentGeometryProgram = '';
  15182. _currentMaterialId = - 1;
  15183. _currentCamera = null;
  15184. // update scene graph
  15185. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15186. // update camera matrices and frustum
  15187. if ( camera.parent === null ) camera.updateMatrixWorld();
  15188. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15189. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15190. _frustum.setFromMatrix( _projScreenMatrix );
  15191. lights.length = 0;
  15192. opaqueObjectsLastIndex = - 1;
  15193. transparentObjectsLastIndex = - 1;
  15194. sprites.length = 0;
  15195. lensFlares.length = 0;
  15196. projectObject( scene, camera );
  15197. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15198. transparentObjects.length = transparentObjectsLastIndex + 1;
  15199. if ( _this.sortObjects === true ) {
  15200. opaqueObjects.sort( painterSortStable );
  15201. transparentObjects.sort( reversePainterSortStable );
  15202. }
  15203. setupLights( lights, camera );
  15204. //
  15205. shadowMap.render( scene, camera );
  15206. //
  15207. _infoRender.calls = 0;
  15208. _infoRender.vertices = 0;
  15209. _infoRender.faces = 0;
  15210. _infoRender.points = 0;
  15211. this.setRenderTarget( renderTarget );
  15212. if ( this.autoClear || forceClear ) {
  15213. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15214. }
  15215. //
  15216. if ( scene.overrideMaterial ) {
  15217. var overrideMaterial = scene.overrideMaterial;
  15218. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  15219. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  15220. } else {
  15221. // opaque pass (front-to-back order)
  15222. state.setBlending( THREE.NoBlending );
  15223. renderObjects( opaqueObjects, camera, fog );
  15224. // transparent pass (back-to-front order)
  15225. renderObjects( transparentObjects, camera, fog );
  15226. }
  15227. // custom render plugins (post pass)
  15228. spritePlugin.render( scene, camera );
  15229. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  15230. // Generate mipmap if we're using any kind of mipmap filtering
  15231. if ( renderTarget ) {
  15232. var texture = renderTarget.texture;
  15233. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15234. texture.minFilter !== THREE.NearestFilter &&
  15235. texture.minFilter !== THREE.LinearFilter ) {
  15236. updateRenderTargetMipmap( renderTarget );
  15237. }
  15238. }
  15239. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15240. state.setDepthTest( true );
  15241. state.setDepthWrite( true );
  15242. state.setColorWrite( true );
  15243. // _gl.finish();
  15244. };
  15245. function pushRenderItem( object, geometry, material, z, group ) {
  15246. var array, index;
  15247. // allocate the next position in the appropriate array
  15248. if ( material.transparent ) {
  15249. array = transparentObjects;
  15250. index = ++ transparentObjectsLastIndex;
  15251. } else {
  15252. array = opaqueObjects;
  15253. index = ++ opaqueObjectsLastIndex;
  15254. }
  15255. // recycle existing render item or grow the array
  15256. var renderItem = array[ index ];
  15257. if ( renderItem !== undefined ) {
  15258. renderItem.id = object.id;
  15259. renderItem.object = object;
  15260. renderItem.geometry = geometry;
  15261. renderItem.material = material;
  15262. renderItem.z = _vector3.z;
  15263. renderItem.group = group;
  15264. } else {
  15265. renderItem = {
  15266. id: object.id,
  15267. object: object,
  15268. geometry: geometry,
  15269. material: material,
  15270. z: _vector3.z,
  15271. group: group
  15272. };
  15273. // assert( index === array.length );
  15274. array.push( renderItem );
  15275. }
  15276. }
  15277. function projectObject( object, camera ) {
  15278. if ( object.visible === false ) return;
  15279. if ( object.layers.test( camera.layers ) ) {
  15280. if ( object instanceof THREE.Light ) {
  15281. lights.push( object );
  15282. } else if ( object instanceof THREE.Sprite ) {
  15283. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15284. sprites.push( object );
  15285. }
  15286. } else if ( object instanceof THREE.LensFlare ) {
  15287. lensFlares.push( object );
  15288. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15289. if ( _this.sortObjects === true ) {
  15290. _vector3.setFromMatrixPosition( object.matrixWorld );
  15291. _vector3.applyProjection( _projScreenMatrix );
  15292. }
  15293. pushRenderItem( object, null, object.material, _vector3.z, null );
  15294. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15295. if ( object instanceof THREE.SkinnedMesh ) {
  15296. object.skeleton.update();
  15297. }
  15298. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15299. var material = object.material;
  15300. if ( material.visible === true ) {
  15301. if ( _this.sortObjects === true ) {
  15302. _vector3.setFromMatrixPosition( object.matrixWorld );
  15303. _vector3.applyProjection( _projScreenMatrix );
  15304. }
  15305. var geometry = objects.update( object );
  15306. if ( material instanceof THREE.MeshFaceMaterial ) {
  15307. var groups = geometry.groups;
  15308. var materials = material.materials;
  15309. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15310. var group = groups[ i ];
  15311. var groupMaterial = materials[ group.materialIndex ];
  15312. if ( groupMaterial.visible === true ) {
  15313. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15314. }
  15315. }
  15316. } else {
  15317. pushRenderItem( object, geometry, material, _vector3.z, null );
  15318. }
  15319. }
  15320. }
  15321. }
  15322. }
  15323. var children = object.children;
  15324. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15325. projectObject( children[ i ], camera );
  15326. }
  15327. }
  15328. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  15329. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15330. var renderItem = renderList[ i ];
  15331. var object = renderItem.object;
  15332. var geometry = renderItem.geometry;
  15333. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15334. var group = renderItem.group;
  15335. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15336. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15337. if ( object instanceof THREE.ImmediateRenderObject ) {
  15338. setMaterial( material );
  15339. var program = setProgram( camera, fog, material, object );
  15340. _currentGeometryProgram = '';
  15341. object.render( function ( object ) {
  15342. _this.renderBufferImmediate( object, program, material );
  15343. } );
  15344. } else {
  15345. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  15346. }
  15347. }
  15348. }
  15349. function initMaterial( material, fog, object ) {
  15350. var materialProperties = properties.get( material );
  15351. var parameters = programCache.getParameters( material, _lights, fog, object );
  15352. var code = programCache.getProgramCode( material, parameters );
  15353. var program = materialProperties.program;
  15354. var programChange = true;
  15355. if ( program === undefined ) {
  15356. // new material
  15357. material.addEventListener( 'dispose', onMaterialDispose );
  15358. } else if ( program.code !== code ) {
  15359. // changed glsl or parameters
  15360. releaseMaterialProgramReference( material );
  15361. } else if ( parameters.shaderID !== undefined ) {
  15362. // same glsl and uniform list
  15363. return;
  15364. } else {
  15365. // only rebuild uniform list
  15366. programChange = false;
  15367. }
  15368. if ( programChange ) {
  15369. if ( parameters.shaderID ) {
  15370. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15371. materialProperties.__webglShader = {
  15372. name: material.type,
  15373. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15374. vertexShader: shader.vertexShader,
  15375. fragmentShader: shader.fragmentShader
  15376. };
  15377. } else {
  15378. materialProperties.__webglShader = {
  15379. name: material.type,
  15380. uniforms: material.uniforms,
  15381. vertexShader: material.vertexShader,
  15382. fragmentShader: material.fragmentShader
  15383. };
  15384. }
  15385. material.__webglShader = materialProperties.__webglShader;
  15386. program = programCache.acquireProgram( material, parameters, code );
  15387. materialProperties.program = program;
  15388. material.program = program;
  15389. }
  15390. var attributes = program.getAttributes();
  15391. if ( material.morphTargets ) {
  15392. material.numSupportedMorphTargets = 0;
  15393. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15394. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15395. material.numSupportedMorphTargets ++;
  15396. }
  15397. }
  15398. }
  15399. if ( material.morphNormals ) {
  15400. material.numSupportedMorphNormals = 0;
  15401. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  15402. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15403. material.numSupportedMorphNormals ++;
  15404. }
  15405. }
  15406. }
  15407. materialProperties.uniformsList = [];
  15408. var uniforms = materialProperties.__webglShader.uniforms,
  15409. uniformLocations = materialProperties.program.getUniforms();
  15410. for ( var u in uniforms ) {
  15411. var location = uniformLocations[ u ];
  15412. if ( location ) {
  15413. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  15414. }
  15415. }
  15416. if ( material instanceof THREE.MeshPhongMaterial ||
  15417. material instanceof THREE.MeshLambertMaterial ||
  15418. material instanceof THREE.MeshStandardMaterial ||
  15419. material.lights ) {
  15420. // store the light setup it was created for
  15421. materialProperties.lightsHash = _lights.hash;
  15422. // wire up the material to this renderer's lighting state
  15423. uniforms.ambientLightColor.value = _lights.ambient;
  15424. uniforms.directionalLights.value = _lights.directional;
  15425. uniforms.pointLights.value = _lights.point;
  15426. uniforms.spotLights.value = _lights.spot;
  15427. uniforms.hemisphereLights.value = _lights.hemi;
  15428. }
  15429. // detect dynamic uniforms
  15430. materialProperties.hasDynamicUniforms = false;
  15431. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  15432. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  15433. if ( uniform.dynamic === true ) {
  15434. materialProperties.hasDynamicUniforms = true;
  15435. break;
  15436. }
  15437. }
  15438. }
  15439. function setMaterial( material ) {
  15440. setMaterialFaces( material );
  15441. if ( material.transparent === true ) {
  15442. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  15443. } else {
  15444. state.setBlending( THREE.NoBlending );
  15445. }
  15446. state.setDepthFunc( material.depthFunc );
  15447. state.setDepthTest( material.depthTest );
  15448. state.setDepthWrite( material.depthWrite );
  15449. state.setColorWrite( material.colorWrite );
  15450. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15451. }
  15452. function setMaterialFaces( material ) {
  15453. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15454. state.setFlipSided( material.side === THREE.BackSide );
  15455. }
  15456. function setProgram( camera, fog, material, object ) {
  15457. _usedTextureUnits = 0;
  15458. var materialProperties = properties.get( material );
  15459. if ( materialProperties.program === undefined ) {
  15460. material.needsUpdate = true;
  15461. }
  15462. if ( materialProperties.lightsHash !== undefined &&
  15463. materialProperties.lightsHash !== _lights.hash ) {
  15464. material.needsUpdate = true;
  15465. }
  15466. if ( material.needsUpdate ) {
  15467. initMaterial( material, fog, object );
  15468. material.needsUpdate = false;
  15469. }
  15470. var refreshProgram = false;
  15471. var refreshMaterial = false;
  15472. var refreshLights = false;
  15473. var program = materialProperties.program,
  15474. p_uniforms = program.getUniforms(),
  15475. m_uniforms = materialProperties.__webglShader.uniforms;
  15476. if ( program.id !== _currentProgram ) {
  15477. _gl.useProgram( program.program );
  15478. _currentProgram = program.id;
  15479. refreshProgram = true;
  15480. refreshMaterial = true;
  15481. refreshLights = true;
  15482. }
  15483. if ( material.id !== _currentMaterialId ) {
  15484. _currentMaterialId = material.id;
  15485. refreshMaterial = true;
  15486. }
  15487. if ( refreshProgram || camera !== _currentCamera ) {
  15488. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15489. if ( capabilities.logarithmicDepthBuffer ) {
  15490. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15491. }
  15492. if ( camera !== _currentCamera ) {
  15493. _currentCamera = camera;
  15494. // lighting uniforms depend on the camera so enforce an update
  15495. // now, in case this material supports lights - or later, when
  15496. // the next material that does gets activated:
  15497. refreshMaterial = true; // set to true on material change
  15498. refreshLights = true; // remains set until update done
  15499. }
  15500. // load material specific uniforms
  15501. // (shader material also gets them for the sake of genericity)
  15502. if ( material instanceof THREE.ShaderMaterial ||
  15503. material instanceof THREE.MeshPhongMaterial ||
  15504. material instanceof THREE.MeshStandardMaterial ||
  15505. material.envMap ) {
  15506. if ( p_uniforms.cameraPosition !== undefined ) {
  15507. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15508. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15509. }
  15510. }
  15511. if ( material instanceof THREE.MeshPhongMaterial ||
  15512. material instanceof THREE.MeshLambertMaterial ||
  15513. material instanceof THREE.MeshBasicMaterial ||
  15514. material instanceof THREE.MeshStandardMaterial ||
  15515. material instanceof THREE.ShaderMaterial ||
  15516. material.skinning ) {
  15517. if ( p_uniforms.viewMatrix !== undefined ) {
  15518. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15519. }
  15520. }
  15521. }
  15522. // skinning uniforms must be set even if material didn't change
  15523. // auto-setting of texture unit for bone texture must go before other textures
  15524. // not sure why, but otherwise weird things happen
  15525. if ( material.skinning ) {
  15526. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  15527. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  15528. }
  15529. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  15530. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  15531. }
  15532. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  15533. if ( p_uniforms.boneTexture !== undefined ) {
  15534. var textureUnit = getTextureUnit();
  15535. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15536. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  15537. }
  15538. if ( p_uniforms.boneTextureWidth !== undefined ) {
  15539. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  15540. }
  15541. if ( p_uniforms.boneTextureHeight !== undefined ) {
  15542. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  15543. }
  15544. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  15545. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  15546. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  15547. }
  15548. }
  15549. }
  15550. if ( refreshMaterial ) {
  15551. if ( material instanceof THREE.MeshPhongMaterial ||
  15552. material instanceof THREE.MeshLambertMaterial ||
  15553. material instanceof THREE.MeshStandardMaterial ||
  15554. material.lights ) {
  15555. // the current material requires lighting info
  15556. // note: all lighting uniforms are always set correctly
  15557. // they simply reference the renderer's state for their
  15558. // values
  15559. //
  15560. // use the current material's .needsUpdate flags to set
  15561. // the GL state when required
  15562. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15563. }
  15564. // refresh uniforms common to several materials
  15565. if ( fog && material.fog ) {
  15566. refreshUniformsFog( m_uniforms, fog );
  15567. }
  15568. if ( material instanceof THREE.MeshBasicMaterial ||
  15569. material instanceof THREE.MeshLambertMaterial ||
  15570. material instanceof THREE.MeshPhongMaterial ||
  15571. material instanceof THREE.MeshStandardMaterial ) {
  15572. refreshUniformsCommon( m_uniforms, material );
  15573. }
  15574. // refresh single material specific uniforms
  15575. if ( material instanceof THREE.LineBasicMaterial ) {
  15576. refreshUniformsLine( m_uniforms, material );
  15577. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15578. refreshUniformsLine( m_uniforms, material );
  15579. refreshUniformsDash( m_uniforms, material );
  15580. } else if ( material instanceof THREE.PointsMaterial ) {
  15581. refreshUniformsPoints( m_uniforms, material );
  15582. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15583. refreshUniformsPhong( m_uniforms, material );
  15584. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  15585. refreshUniformsStandard( m_uniforms, material );
  15586. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15587. m_uniforms.mNear.value = camera.near;
  15588. m_uniforms.mFar.value = camera.far;
  15589. m_uniforms.opacity.value = material.opacity;
  15590. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15591. m_uniforms.opacity.value = material.opacity;
  15592. }
  15593. if ( shadowMap.enabled ) {
  15594. if ( object.receiveShadow && ! material._shadowPass ) {
  15595. refreshUniformsShadow( m_uniforms, camera );
  15596. }
  15597. }
  15598. // load common uniforms
  15599. loadUniformsGeneric( materialProperties.uniformsList );
  15600. }
  15601. loadUniformsMatrices( p_uniforms, object );
  15602. if ( p_uniforms.modelMatrix !== undefined ) {
  15603. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15604. }
  15605. if ( materialProperties.hasDynamicUniforms === true ) {
  15606. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  15607. }
  15608. return program;
  15609. }
  15610. function updateDynamicUniforms ( uniforms, object, camera ) {
  15611. var dynamicUniforms = [];
  15612. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15613. var uniform = uniforms[ j ][ 0 ];
  15614. var onUpdateCallback = uniform.onUpdateCallback;
  15615. if ( onUpdateCallback !== undefined ) {
  15616. onUpdateCallback.bind( uniform )( object, camera );
  15617. dynamicUniforms.push( uniforms[ j ] );
  15618. }
  15619. }
  15620. loadUniformsGeneric( dynamicUniforms );
  15621. }
  15622. // Uniforms (refresh uniforms objects)
  15623. function refreshUniformsCommon ( uniforms, material ) {
  15624. uniforms.opacity.value = material.opacity;
  15625. uniforms.diffuse.value = material.color;
  15626. if ( material.emissive ) {
  15627. uniforms.emissive.value = material.emissive;
  15628. }
  15629. uniforms.map.value = material.map;
  15630. uniforms.specularMap.value = material.specularMap;
  15631. uniforms.alphaMap.value = material.alphaMap;
  15632. if ( material.aoMap ) {
  15633. uniforms.aoMap.value = material.aoMap;
  15634. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15635. }
  15636. // uv repeat and offset setting priorities
  15637. // 1. color map
  15638. // 2. specular map
  15639. // 3. normal map
  15640. // 4. bump map
  15641. // 5. alpha map
  15642. // 6. emissive map
  15643. var uvScaleMap;
  15644. if ( material.map ) {
  15645. uvScaleMap = material.map;
  15646. } else if ( material.specularMap ) {
  15647. uvScaleMap = material.specularMap;
  15648. } else if ( material.displacementMap ) {
  15649. uvScaleMap = material.displacementMap;
  15650. } else if ( material.normalMap ) {
  15651. uvScaleMap = material.normalMap;
  15652. } else if ( material.bumpMap ) {
  15653. uvScaleMap = material.bumpMap;
  15654. } else if ( material.alphaMap ) {
  15655. uvScaleMap = material.alphaMap;
  15656. } else if ( material.emissiveMap ) {
  15657. uvScaleMap = material.emissiveMap;
  15658. }
  15659. if ( uvScaleMap !== undefined ) {
  15660. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) uvScaleMap = uvScaleMap.texture;
  15661. var offset = uvScaleMap.offset;
  15662. var repeat = uvScaleMap.repeat;
  15663. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15664. }
  15665. uniforms.envMap.value = material.envMap;
  15666. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15667. uniforms.reflectivity.value = material.reflectivity;
  15668. uniforms.refractionRatio.value = material.refractionRatio;
  15669. }
  15670. function refreshUniformsLine ( uniforms, material ) {
  15671. uniforms.diffuse.value = material.color;
  15672. uniforms.opacity.value = material.opacity;
  15673. }
  15674. function refreshUniformsDash ( uniforms, material ) {
  15675. uniforms.dashSize.value = material.dashSize;
  15676. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15677. uniforms.scale.value = material.scale;
  15678. }
  15679. function refreshUniformsPoints ( uniforms, material ) {
  15680. uniforms.psColor.value = material.color;
  15681. uniforms.opacity.value = material.opacity;
  15682. uniforms.size.value = material.size * pixelRatio;
  15683. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15684. uniforms.map.value = material.map;
  15685. if ( material.map !== null ) {
  15686. var offset = material.map.offset;
  15687. var repeat = material.map.repeat;
  15688. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15689. }
  15690. }
  15691. function refreshUniformsFog ( uniforms, fog ) {
  15692. uniforms.fogColor.value = fog.color;
  15693. if ( fog instanceof THREE.Fog ) {
  15694. uniforms.fogNear.value = fog.near;
  15695. uniforms.fogFar.value = fog.far;
  15696. } else if ( fog instanceof THREE.FogExp2 ) {
  15697. uniforms.fogDensity.value = fog.density;
  15698. }
  15699. }
  15700. function refreshUniformsPhong ( uniforms, material ) {
  15701. uniforms.specular.value = material.specular;
  15702. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15703. if ( material.lightMap ) {
  15704. uniforms.lightMap.value = material.lightMap;
  15705. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15706. }
  15707. if ( material.emissiveMap ) {
  15708. uniforms.emissiveMap.value = material.emissiveMap;
  15709. }
  15710. if ( material.bumpMap ) {
  15711. uniforms.bumpMap.value = material.bumpMap;
  15712. uniforms.bumpScale.value = material.bumpScale;
  15713. }
  15714. if ( material.normalMap ) {
  15715. uniforms.normalMap.value = material.normalMap;
  15716. uniforms.normalScale.value.copy( material.normalScale );
  15717. }
  15718. if ( material.displacementMap ) {
  15719. uniforms.displacementMap.value = material.displacementMap;
  15720. uniforms.displacementScale.value = material.displacementScale;
  15721. uniforms.displacementBias.value = material.displacementBias;
  15722. }
  15723. }
  15724. function refreshUniformsStandard ( uniforms, material ) {
  15725. uniforms.roughness.value = material.roughness;
  15726. //uniforms.reflectivity.value = material.reflectivity; // part of uniforms common
  15727. uniforms.metalness.value = material.metalness;
  15728. if ( material.roughnessMap ) {
  15729. uniforms.roughnessMap.value = material.roughnessMap;
  15730. }
  15731. if ( material.reflectivityMap ) {
  15732. uniforms.reflectivityMap.value = material.reflectivityMap;
  15733. }
  15734. if ( material.metalnessMap ) {
  15735. uniforms.metalnessMap.value = material.metalnessMap;
  15736. }
  15737. if ( material.lightMap ) {
  15738. uniforms.lightMap.value = material.lightMap;
  15739. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15740. }
  15741. if ( material.emissiveMap ) {
  15742. uniforms.emissiveMap.value = material.emissiveMap;
  15743. }
  15744. if ( material.bumpMap ) {
  15745. uniforms.bumpMap.value = material.bumpMap;
  15746. uniforms.bumpScale.value = material.bumpScale;
  15747. }
  15748. if ( material.normalMap ) {
  15749. uniforms.normalMap.value = material.normalMap;
  15750. uniforms.normalScale.value.copy( material.normalScale );
  15751. }
  15752. if ( material.displacementMap ) {
  15753. uniforms.displacementMap.value = material.displacementMap;
  15754. uniforms.displacementScale.value = material.displacementScale;
  15755. uniforms.displacementBias.value = material.displacementBias;
  15756. }
  15757. if ( material.envMap ) {
  15758. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15759. uniforms.envMapIntensity.value = material.envMapIntensity;
  15760. }
  15761. }
  15762. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15763. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  15764. uniforms.ambientLightColor.needsUpdate = value;
  15765. uniforms.directionalLights.needsUpdate = value;
  15766. uniforms.pointLights.needsUpdate = value;
  15767. uniforms.spotLights.needsUpdate = value;
  15768. uniforms.hemisphereLights.needsUpdate = value;
  15769. }
  15770. function refreshUniformsShadow ( uniforms, camera ) {
  15771. if ( uniforms.shadowMatrix ) {
  15772. var j = 0;
  15773. var shadows = _lights.shadows;
  15774. for ( var i = 0, il = shadows.length; i < il; i ++ ) {
  15775. var light = shadows[ i ];
  15776. if ( light instanceof THREE.PointLight || light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) {
  15777. var shadow = light.shadow;
  15778. if ( light instanceof THREE.PointLight ) {
  15779. // for point lights we set the shadow matrix to be a translation-only matrix
  15780. // equal to inverse of the light's position
  15781. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  15782. shadow.matrix.identity().setPosition( _vector3 );
  15783. // for point lights we set the sign of the shadowDarkness uniform to be negative
  15784. uniforms.shadowDarkness.value[ j ] = - shadow.darkness;
  15785. } else {
  15786. uniforms.shadowDarkness.value[ j ] = shadow.darkness;
  15787. }
  15788. uniforms.shadowMatrix.value[ j ] = shadow.matrix;
  15789. uniforms.shadowMap.value[ j ] = shadow.map;
  15790. uniforms.shadowMapSize.value[ j ] = shadow.mapSize;
  15791. uniforms.shadowBias.value[ j ] = shadow.bias;
  15792. j ++;
  15793. }
  15794. }
  15795. }
  15796. }
  15797. // Uniforms (load to GPU)
  15798. function loadUniformsMatrices ( uniforms, object ) {
  15799. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  15800. if ( uniforms.normalMatrix ) {
  15801. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  15802. }
  15803. }
  15804. function getTextureUnit() {
  15805. var textureUnit = _usedTextureUnits;
  15806. if ( textureUnit >= capabilities.maxTextures ) {
  15807. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  15808. }
  15809. _usedTextureUnits += 1;
  15810. return textureUnit;
  15811. }
  15812. function loadUniformsGeneric ( uniforms ) {
  15813. var texture, textureUnit;
  15814. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15815. var uniform = uniforms[ j ][ 0 ];
  15816. // needsUpdate property is not added to all uniforms.
  15817. if ( uniform.needsUpdate === false ) continue;
  15818. var type = uniform.type;
  15819. var value = uniform.value;
  15820. var location = uniforms[ j ][ 1 ];
  15821. switch ( type ) {
  15822. case '1i':
  15823. _gl.uniform1i( location, value );
  15824. break;
  15825. case '1f':
  15826. _gl.uniform1f( location, value );
  15827. break;
  15828. case '2f':
  15829. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  15830. break;
  15831. case '3f':
  15832. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  15833. break;
  15834. case '4f':
  15835. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  15836. break;
  15837. case '1iv':
  15838. _gl.uniform1iv( location, value );
  15839. break;
  15840. case '3iv':
  15841. _gl.uniform3iv( location, value );
  15842. break;
  15843. case '1fv':
  15844. _gl.uniform1fv( location, value );
  15845. break;
  15846. case '2fv':
  15847. _gl.uniform2fv( location, value );
  15848. break;
  15849. case '3fv':
  15850. _gl.uniform3fv( location, value );
  15851. break;
  15852. case '4fv':
  15853. _gl.uniform4fv( location, value );
  15854. break;
  15855. case 'Matrix2fv':
  15856. _gl.uniformMatrix2fv( location, false, value );
  15857. break;
  15858. case 'Matrix3fv':
  15859. _gl.uniformMatrix3fv( location, false, value );
  15860. break;
  15861. case 'Matrix4fv':
  15862. _gl.uniformMatrix4fv( location, false, value );
  15863. break;
  15864. //
  15865. case 'i':
  15866. // single integer
  15867. _gl.uniform1i( location, value );
  15868. break;
  15869. case 'f':
  15870. // single float
  15871. _gl.uniform1f( location, value );
  15872. break;
  15873. case 'v2':
  15874. // single THREE.Vector2
  15875. _gl.uniform2f( location, value.x, value.y );
  15876. break;
  15877. case 'v3':
  15878. // single THREE.Vector3
  15879. _gl.uniform3f( location, value.x, value.y, value.z );
  15880. break;
  15881. case 'v4':
  15882. // single THREE.Vector4
  15883. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15884. break;
  15885. case 'c':
  15886. // single THREE.Color
  15887. _gl.uniform3f( location, value.r, value.g, value.b );
  15888. break;
  15889. case 's':
  15890. // TODO: Optimize this.
  15891. for( var propertyName in uniform.properties ) {
  15892. var property = uniform.properties[ propertyName ];
  15893. var locationProperty = location[ propertyName ];
  15894. var valueProperty = value[ propertyName ];
  15895. switch( property.type ) {
  15896. case 'i':
  15897. _gl.uniform1i( locationProperty, valueProperty );
  15898. break;
  15899. case 'f':
  15900. _gl.uniform1f( locationProperty, valueProperty );
  15901. break;
  15902. case 'v2':
  15903. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  15904. break;
  15905. case 'v3':
  15906. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  15907. break;
  15908. case 'v4':
  15909. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  15910. break;
  15911. case 'c':
  15912. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  15913. break;
  15914. };
  15915. }
  15916. break;
  15917. case 'sa':
  15918. // TODO: Optimize this.
  15919. for( var i = 0; i < value.length; i ++ ) {
  15920. for( var propertyName in uniform.properties ) {
  15921. var property = uniform.properties[ propertyName ];
  15922. var locationProperty = location[ i ][ propertyName ];
  15923. var valueProperty = value[i][ propertyName ];
  15924. switch( property.type ) {
  15925. case 'i':
  15926. _gl.uniform1i( locationProperty, valueProperty );
  15927. break;
  15928. case 'f':
  15929. _gl.uniform1f( locationProperty, valueProperty );
  15930. break;
  15931. case 'v2':
  15932. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  15933. break;
  15934. case 'v3':
  15935. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  15936. break;
  15937. case 'v4':
  15938. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  15939. break;
  15940. case 'c':
  15941. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  15942. break;
  15943. };
  15944. }
  15945. }
  15946. break;
  15947. case 'iv1':
  15948. // flat array of integers (JS or typed array)
  15949. _gl.uniform1iv( location, value );
  15950. break;
  15951. case 'iv':
  15952. // flat array of integers with 3 x N size (JS or typed array)
  15953. _gl.uniform3iv( location, value );
  15954. break;
  15955. case 'fv1':
  15956. // flat array of floats (JS or typed array)
  15957. _gl.uniform1fv( location, value );
  15958. break;
  15959. case 'fv':
  15960. // flat array of floats with 3 x N size (JS or typed array)
  15961. _gl.uniform3fv( location, value );
  15962. break;
  15963. case 'v2v':
  15964. // array of THREE.Vector2
  15965. if ( uniform._array === undefined ) {
  15966. uniform._array = new Float32Array( 2 * value.length );
  15967. }
  15968. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  15969. uniform._array[ i2 + 0 ] = value[ i ].x;
  15970. uniform._array[ i2 + 1 ] = value[ i ].y;
  15971. }
  15972. _gl.uniform2fv( location, uniform._array );
  15973. break;
  15974. case 'v3v':
  15975. // array of THREE.Vector3
  15976. if ( uniform._array === undefined ) {
  15977. uniform._array = new Float32Array( 3 * value.length );
  15978. }
  15979. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  15980. uniform._array[ i3 + 0 ] = value[ i ].x;
  15981. uniform._array[ i3 + 1 ] = value[ i ].y;
  15982. uniform._array[ i3 + 2 ] = value[ i ].z;
  15983. }
  15984. _gl.uniform3fv( location, uniform._array );
  15985. break;
  15986. case 'v4v':
  15987. // array of THREE.Vector4
  15988. if ( uniform._array === undefined ) {
  15989. uniform._array = new Float32Array( 4 * value.length );
  15990. }
  15991. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  15992. uniform._array[ i4 + 0 ] = value[ i ].x;
  15993. uniform._array[ i4 + 1 ] = value[ i ].y;
  15994. uniform._array[ i4 + 2 ] = value[ i ].z;
  15995. uniform._array[ i4 + 3 ] = value[ i ].w;
  15996. }
  15997. _gl.uniform4fv( location, uniform._array );
  15998. break;
  15999. case 'm2':
  16000. // single THREE.Matrix2
  16001. _gl.uniformMatrix2fv( location, false, value.elements );
  16002. break;
  16003. case 'm3':
  16004. // single THREE.Matrix3
  16005. _gl.uniformMatrix3fv( location, false, value.elements );
  16006. break;
  16007. case 'm3v':
  16008. // array of THREE.Matrix3
  16009. if ( uniform._array === undefined ) {
  16010. uniform._array = new Float32Array( 9 * value.length );
  16011. }
  16012. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16013. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  16014. }
  16015. _gl.uniformMatrix3fv( location, false, uniform._array );
  16016. break;
  16017. case 'm4':
  16018. // single THREE.Matrix4
  16019. _gl.uniformMatrix4fv( location, false, value.elements );
  16020. break;
  16021. case 'm4v':
  16022. // array of THREE.Matrix4
  16023. if ( uniform._array === undefined ) {
  16024. uniform._array = new Float32Array( 16 * value.length );
  16025. }
  16026. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16027. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  16028. }
  16029. _gl.uniformMatrix4fv( location, false, uniform._array );
  16030. break;
  16031. case 't':
  16032. // single THREE.Texture (2d or cube)
  16033. texture = value;
  16034. textureUnit = getTextureUnit();
  16035. _gl.uniform1i( location, textureUnit );
  16036. if ( ! texture ) continue;
  16037. if ( texture instanceof THREE.CubeTexture ||
  16038. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  16039. // CompressedTexture can have Array in image :/
  16040. setCubeTexture( texture, textureUnit );
  16041. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16042. setCubeTextureDynamic( texture.texture, textureUnit );
  16043. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16044. _this.setTexture( texture.texture, textureUnit );
  16045. } else {
  16046. _this.setTexture( texture, textureUnit );
  16047. }
  16048. break;
  16049. case 'tv':
  16050. // array of THREE.Texture (2d or cube)
  16051. if ( uniform._array === undefined ) {
  16052. uniform._array = [];
  16053. }
  16054. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16055. uniform._array[ i ] = getTextureUnit();
  16056. }
  16057. _gl.uniform1iv( location, uniform._array );
  16058. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16059. texture = uniform.value[ i ];
  16060. textureUnit = uniform._array[ i ];
  16061. if ( ! texture ) continue;
  16062. if ( texture instanceof THREE.CubeTexture ||
  16063. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  16064. // CompressedTexture can have Array in image :/
  16065. setCubeTexture( texture, textureUnit );
  16066. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16067. _this.setTexture( texture.texture, textureUnit );
  16068. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16069. setCubeTextureDynamic( texture.texture, textureUnit );
  16070. } else {
  16071. _this.setTexture( texture, textureUnit );
  16072. }
  16073. }
  16074. break;
  16075. default:
  16076. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  16077. }
  16078. }
  16079. }
  16080. function setupLights ( lights, camera ) {
  16081. var l, ll, light,
  16082. r = 0, g = 0, b = 0,
  16083. color,
  16084. intensity,
  16085. distance,
  16086. viewMatrix = camera.matrixWorldInverse,
  16087. directionalLength = 0,
  16088. pointLength = 0,
  16089. spotLength = 0,
  16090. hemiLength = 0,
  16091. shadowsLength = 0;
  16092. _lights.shadowsPointLight = 0;
  16093. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  16094. light = lights[ l ];
  16095. color = light.color;
  16096. intensity = light.intensity;
  16097. distance = light.distance;
  16098. if ( light instanceof THREE.AmbientLight ) {
  16099. r += color.r;
  16100. g += color.g;
  16101. b += color.b;
  16102. } else if ( light instanceof THREE.DirectionalLight ) {
  16103. if( ! light.__webglUniforms ) {
  16104. light.__webglUniforms = {
  16105. direction: new THREE.Vector3(),
  16106. color: new THREE.Color(),
  16107. shadow: -1
  16108. }
  16109. }
  16110. var uniforms = light.__webglUniforms;
  16111. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16112. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16113. uniforms.direction.sub( _vector3 );
  16114. uniforms.direction.transformDirection( viewMatrix );
  16115. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16116. if ( light.castShadow ) {
  16117. uniforms.shadow = shadowsLength;
  16118. _lights.shadows[ shadowsLength ++ ] = light;
  16119. } else {
  16120. uniforms.shadow = -1;
  16121. }
  16122. _lights.directional[ directionalLength ++ ] = uniforms;
  16123. } else if ( light instanceof THREE.PointLight ) {
  16124. if( ! light.__webglUniforms ) {
  16125. light.__webglUniforms = {
  16126. position: new THREE.Vector3(),
  16127. color: new THREE.Color(),
  16128. distance: 0,
  16129. decay: 0,
  16130. shadow: -1
  16131. }
  16132. }
  16133. var uniforms = light.__webglUniforms;
  16134. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16135. uniforms.position.applyMatrix4( viewMatrix );
  16136. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16137. uniforms.distance = light.distance;
  16138. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16139. if ( light.castShadow ) {
  16140. uniforms.shadow = shadowsLength;
  16141. _lights.shadows[ shadowsLength ++ ] = light;
  16142. _lights.shadowsPointLight ++;
  16143. } else {
  16144. uniforms.shadow = -1;
  16145. }
  16146. _lights.point[ pointLength ++ ] = uniforms;
  16147. } else if ( light instanceof THREE.SpotLight ) {
  16148. if( ! light.__webglUniforms ) {
  16149. light.__webglUniforms = {
  16150. position: new THREE.Vector3(),
  16151. direction: new THREE.Vector3(),
  16152. color: new THREE.Color(),
  16153. distance: 0,
  16154. decay: 0,
  16155. angleCos: 0
  16156. }
  16157. }
  16158. var uniforms = light.__webglUniforms;
  16159. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16160. uniforms.position.applyMatrix4( viewMatrix );
  16161. uniforms.color.copy( color ).multiplyScalar( intensity );
  16162. uniforms.distance = distance;
  16163. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16164. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16165. uniforms.direction.sub( _vector3 );
  16166. uniforms.direction.transformDirection( viewMatrix );
  16167. uniforms.angleCos = Math.cos( light.angle );
  16168. uniforms.exponent = light.exponent;
  16169. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16170. if ( light.castShadow ) {
  16171. uniforms.shadow = shadowsLength;
  16172. _lights.shadows[ shadowsLength ++ ] = light;
  16173. } else {
  16174. uniforms.shadow = -1;
  16175. }
  16176. _lights.spot[ spotLength ++ ] = uniforms;
  16177. } else if ( light instanceof THREE.HemisphereLight ) {
  16178. if( ! light.__webglUniforms ) {
  16179. light.__webglUniforms = {
  16180. direction: new THREE.Vector3(),
  16181. skyColor: new THREE.Color(),
  16182. groundColor: new THREE.Color()
  16183. }
  16184. }
  16185. var uniforms = light.__webglUniforms;
  16186. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16187. uniforms.direction.transformDirection( viewMatrix );
  16188. uniforms.direction.normalize();
  16189. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16190. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16191. _lights.hemi[ hemiLength ++ ] = uniforms;
  16192. }
  16193. }
  16194. _lights.ambient[ 0 ] = r;
  16195. _lights.ambient[ 1 ] = g;
  16196. _lights.ambient[ 2 ] = b;
  16197. _lights.directional.length = directionalLength;
  16198. _lights.point.length = pointLength;
  16199. _lights.spot.length = spotLength;
  16200. _lights.hemi.length = hemiLength;
  16201. _lights.shadows.length = shadowsLength;
  16202. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + shadowsLength;
  16203. }
  16204. // GL state setting
  16205. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16206. if ( cullFace === THREE.CullFaceNone ) {
  16207. state.disable( _gl.CULL_FACE );
  16208. } else {
  16209. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16210. _gl.frontFace( _gl.CW );
  16211. } else {
  16212. _gl.frontFace( _gl.CCW );
  16213. }
  16214. if ( cullFace === THREE.CullFaceBack ) {
  16215. _gl.cullFace( _gl.BACK );
  16216. } else if ( cullFace === THREE.CullFaceFront ) {
  16217. _gl.cullFace( _gl.FRONT );
  16218. } else {
  16219. _gl.cullFace( _gl.FRONT_AND_BACK );
  16220. }
  16221. state.enable( _gl.CULL_FACE );
  16222. }
  16223. };
  16224. // Textures
  16225. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  16226. var extension;
  16227. if ( isImagePowerOfTwo ) {
  16228. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16229. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16230. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16231. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16232. } else {
  16233. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16234. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16235. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16236. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16237. }
  16238. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16239. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16240. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16241. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16242. }
  16243. }
  16244. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16245. if ( extension ) {
  16246. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16247. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16248. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16249. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16250. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16251. }
  16252. }
  16253. }
  16254. function uploadTexture( textureProperties, texture, slot ) {
  16255. if ( textureProperties.__webglInit === undefined ) {
  16256. textureProperties.__webglInit = true;
  16257. texture.addEventListener( 'dispose', onTextureDispose );
  16258. textureProperties.__webglTexture = _gl.createTexture();
  16259. _infoMemory.textures ++;
  16260. }
  16261. state.activeTexture( _gl.TEXTURE0 + slot );
  16262. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16263. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16264. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16265. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16266. texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16267. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {
  16268. texture.image = makePowerOfTwo( texture.image );
  16269. }
  16270. var image = texture.image,
  16271. isImagePowerOfTwo = isPowerOfTwo( image ),
  16272. glFormat = paramThreeToGL( texture.format ),
  16273. glType = paramThreeToGL( texture.type );
  16274. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  16275. var mipmap, mipmaps = texture.mipmaps;
  16276. if ( texture instanceof THREE.DataTexture ) {
  16277. // use manually created mipmaps if available
  16278. // if there are no manual mipmaps
  16279. // set 0 level mipmap and then use GL to generate other mipmap levels
  16280. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16281. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16282. mipmap = mipmaps[ i ];
  16283. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16284. }
  16285. texture.generateMipmaps = false;
  16286. } else {
  16287. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16288. }
  16289. } else if ( texture instanceof THREE.CompressedTexture ) {
  16290. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16291. mipmap = mipmaps[ i ];
  16292. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16293. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16294. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16295. } else {
  16296. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16297. }
  16298. } else {
  16299. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16300. }
  16301. }
  16302. } else {
  16303. // regular Texture (image, video, canvas)
  16304. // use manually created mipmaps if available
  16305. // if there are no manual mipmaps
  16306. // set 0 level mipmap and then use GL to generate other mipmap levels
  16307. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16308. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16309. mipmap = mipmaps[ i ];
  16310. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16311. }
  16312. texture.generateMipmaps = false;
  16313. } else {
  16314. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  16315. }
  16316. }
  16317. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16318. textureProperties.__version = texture.version;
  16319. if ( texture.onUpdate ) texture.onUpdate( texture );
  16320. }
  16321. this.setTexture = function ( texture, slot ) {
  16322. var textureProperties = properties.get( texture );
  16323. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16324. var image = texture.image;
  16325. if ( image === undefined ) {
  16326. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16327. return;
  16328. }
  16329. if ( image.complete === false ) {
  16330. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16331. return;
  16332. }
  16333. uploadTexture( textureProperties, texture, slot );
  16334. return;
  16335. }
  16336. state.activeTexture( _gl.TEXTURE0 + slot );
  16337. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16338. };
  16339. function clampToMaxSize ( image, maxSize ) {
  16340. if ( image.width > maxSize || image.height > maxSize ) {
  16341. // Warning: Scaling through the canvas will only work with images that use
  16342. // premultiplied alpha.
  16343. var scale = maxSize / Math.max( image.width, image.height );
  16344. var canvas = document.createElement( 'canvas' );
  16345. canvas.width = Math.floor( image.width * scale );
  16346. canvas.height = Math.floor( image.height * scale );
  16347. var context = canvas.getContext( '2d' );
  16348. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16349. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16350. return canvas;
  16351. }
  16352. return image;
  16353. }
  16354. function isPowerOfTwo( image ) {
  16355. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16356. }
  16357. function textureNeedsPowerOfTwo( texture ) {
  16358. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16359. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16360. return false;
  16361. }
  16362. function makePowerOfTwo( image ) {
  16363. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16364. var canvas = document.createElement( 'canvas' );
  16365. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16366. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16367. var context = canvas.getContext( '2d' );
  16368. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16369. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16370. return canvas;
  16371. }
  16372. return image;
  16373. }
  16374. function setCubeTexture ( texture, slot ) {
  16375. var textureProperties = properties.get( texture );
  16376. if ( texture.image.length === 6 ) {
  16377. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16378. if ( ! textureProperties.__image__webglTextureCube ) {
  16379. texture.addEventListener( 'dispose', onTextureDispose );
  16380. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16381. _infoMemory.textures ++;
  16382. }
  16383. state.activeTexture( _gl.TEXTURE0 + slot );
  16384. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16385. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16386. var isCompressed = texture instanceof THREE.CompressedTexture;
  16387. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16388. var cubeImage = [];
  16389. for ( var i = 0; i < 6; i ++ ) {
  16390. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16391. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16392. } else {
  16393. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16394. }
  16395. }
  16396. var image = cubeImage[ 0 ],
  16397. isImagePowerOfTwo = isPowerOfTwo( image ),
  16398. glFormat = paramThreeToGL( texture.format ),
  16399. glType = paramThreeToGL( texture.type );
  16400. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  16401. for ( var i = 0; i < 6; i ++ ) {
  16402. if ( ! isCompressed ) {
  16403. if ( isDataTexture ) {
  16404. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16405. } else {
  16406. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16407. }
  16408. } else {
  16409. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16410. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16411. mipmap = mipmaps[ j ];
  16412. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16413. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16414. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16415. } else {
  16416. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16417. }
  16418. } else {
  16419. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16420. }
  16421. }
  16422. }
  16423. }
  16424. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  16425. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16426. }
  16427. textureProperties.__version = texture.version;
  16428. if ( texture.onUpdate ) texture.onUpdate( texture );
  16429. } else {
  16430. state.activeTexture( _gl.TEXTURE0 + slot );
  16431. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16432. }
  16433. }
  16434. }
  16435. function setCubeTextureDynamic ( texture, slot ) {
  16436. state.activeTexture( _gl.TEXTURE0 + slot );
  16437. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16438. }
  16439. // Render targets
  16440. // Setup storage for target texture and bind it to correct framebuffer
  16441. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  16442. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16443. var glType = paramThreeToGL( renderTarget.texture.type );
  16444. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16445. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16446. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16447. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16448. }
  16449. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16450. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  16451. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16452. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16453. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16454. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16455. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16456. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16457. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16458. } else {
  16459. // FIXME: We don't support !depth !stencil
  16460. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16461. }
  16462. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16463. }
  16464. // Setup GL resources for a non-texture depth buffer
  16465. function setupDepthRenderbuffer( renderTarget ) {
  16466. var renderTargetProperties = properties.get( renderTarget );
  16467. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16468. if ( isCube ) {
  16469. renderTargetProperties.__webglDepthbuffer = [];
  16470. for ( var i = 0; i < 6; i ++ ) {
  16471. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16472. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16473. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16474. }
  16475. }
  16476. else {
  16477. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16478. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16479. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16480. }
  16481. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16482. };
  16483. // Set up GL resources for the render target
  16484. function setupRenderTarget( renderTarget ) {
  16485. var renderTargetProperties = properties.get( renderTarget );
  16486. var textureProperties = properties.get( renderTarget.texture );
  16487. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16488. textureProperties.__webglTexture = _gl.createTexture();
  16489. _infoMemory.textures ++;
  16490. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16491. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  16492. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16493. var glType = paramThreeToGL( renderTarget.texture.type );
  16494. // Setup framebuffer
  16495. if ( isCube ) {
  16496. renderTargetProperties.__webglFramebuffer = [];
  16497. for ( var i = 0; i < 6; i ++ ) {
  16498. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16499. }
  16500. } else {
  16501. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16502. }
  16503. // Setup color buffer
  16504. if ( isCube ) {
  16505. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16506. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16507. for ( var i = 0; i < 6; i ++ ) {
  16508. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16509. }
  16510. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16511. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16512. } else {
  16513. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16514. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16515. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16516. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16517. state.bindTexture( _gl.TEXTURE_2D, null );
  16518. }
  16519. // Setup depth and stencil buffers
  16520. if ( renderTarget.depthBuffer ) {
  16521. setupDepthRenderbuffer( renderTarget );
  16522. }
  16523. }
  16524. this.setRenderTarget = function ( renderTarget ) {
  16525. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16526. setupRenderTarget( renderTarget );
  16527. }
  16528. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16529. var framebuffer, width, height, vx, vy;
  16530. if ( renderTarget ) {
  16531. var renderTargetProperties = properties.get( renderTarget );
  16532. if ( isCube ) {
  16533. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16534. } else {
  16535. framebuffer = renderTargetProperties.__webglFramebuffer;
  16536. }
  16537. width = renderTarget.width;
  16538. height = renderTarget.height;
  16539. vx = 0;
  16540. vy = 0;
  16541. } else {
  16542. framebuffer = null;
  16543. width = _viewportWidth;
  16544. height = _viewportHeight;
  16545. vx = _viewportX;
  16546. vy = _viewportY;
  16547. }
  16548. if ( framebuffer !== _currentFramebuffer ) {
  16549. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16550. _gl.viewport( vx, vy, width, height );
  16551. _currentFramebuffer = framebuffer;
  16552. }
  16553. if ( isCube ) {
  16554. var textureProperties = properties.get( renderTarget.texture );
  16555. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  16556. }
  16557. _currentWidth = width;
  16558. _currentHeight = height;
  16559. };
  16560. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16561. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16562. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16563. return;
  16564. }
  16565. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16566. if ( framebuffer ) {
  16567. var restore = false;
  16568. if ( framebuffer !== _currentFramebuffer ) {
  16569. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16570. restore = true;
  16571. }
  16572. try {
  16573. var texture = renderTarget.texture;
  16574. if ( texture.format !== THREE.RGBAFormat
  16575. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16576. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16577. return;
  16578. }
  16579. if ( texture.type !== THREE.UnsignedByteType
  16580. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  16581. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  16582. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16583. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16584. return;
  16585. }
  16586. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16587. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16588. } else {
  16589. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16590. }
  16591. } finally {
  16592. if ( restore ) {
  16593. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16594. }
  16595. }
  16596. }
  16597. };
  16598. function updateRenderTargetMipmap( renderTarget ) {
  16599. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16600. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16601. state.bindTexture( target, texture );
  16602. _gl.generateMipmap( target );
  16603. state.bindTexture( target, null );
  16604. }
  16605. // Fallback filters for non-power-of-2 textures
  16606. function filterFallback ( f ) {
  16607. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16608. return _gl.NEAREST;
  16609. }
  16610. return _gl.LINEAR;
  16611. }
  16612. // Map three.js constants to WebGL constants
  16613. function paramThreeToGL ( p ) {
  16614. var extension;
  16615. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16616. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16617. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16618. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16619. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16620. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16621. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16622. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16623. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16624. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16625. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16626. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16627. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16628. if ( p === THREE.ByteType ) return _gl.BYTE;
  16629. if ( p === THREE.ShortType ) return _gl.SHORT;
  16630. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16631. if ( p === THREE.IntType ) return _gl.INT;
  16632. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16633. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16634. extension = extensions.get( 'OES_texture_half_float' );
  16635. if ( extension !== null ) {
  16636. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16637. }
  16638. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16639. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16640. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16641. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16642. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16643. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16644. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16645. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16646. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16647. if ( p === THREE.OneFactor ) return _gl.ONE;
  16648. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16649. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16650. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16651. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16652. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16653. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16654. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16655. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16656. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16657. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16658. if ( extension !== null ) {
  16659. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16660. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16661. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16662. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16663. }
  16664. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16665. if ( extension !== null ) {
  16666. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16667. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16668. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16669. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16670. }
  16671. extension = extensions.get( 'EXT_blend_minmax' );
  16672. if ( extension !== null ) {
  16673. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16674. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16675. }
  16676. return 0;
  16677. }
  16678. };
  16679. // File:src/renderers/WebGLRenderTarget.js
  16680. /**
  16681. * @author szimek / https://github.com/szimek/
  16682. * @author alteredq / http://alteredqualia.com/
  16683. * @author Marius Kintel / https://github.com/kintel
  16684. */
  16685. /*
  16686. In options, we can specify:
  16687. * Texture parameters for an auto-generated target texture
  16688. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  16689. */
  16690. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16691. this.uuid = THREE.Math.generateUUID();
  16692. this.width = width;
  16693. this.height = height;
  16694. options = options || {};
  16695. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16696. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy );
  16697. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16698. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16699. };
  16700. THREE.WebGLRenderTarget.prototype = {
  16701. constructor: THREE.WebGLRenderTarget,
  16702. setSize: function ( width, height ) {
  16703. if ( this.width !== width || this.height !== height ) {
  16704. this.width = width;
  16705. this.height = height;
  16706. this.dispose();
  16707. }
  16708. },
  16709. clone: function () {
  16710. return new this.constructor().copy( this );
  16711. },
  16712. copy: function ( source ) {
  16713. this.width = source.width;
  16714. this.height = source.height;
  16715. this.texture = source.texture.clone();
  16716. this.depthBuffer = source.depthBuffer;
  16717. this.stencilBuffer = source.stencilBuffer;
  16718. this.shareDepthFrom = source.shareDepthFrom;
  16719. return this;
  16720. },
  16721. dispose: function () {
  16722. this.dispatchEvent( { type: 'dispose' } );
  16723. }
  16724. };
  16725. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16726. // File:src/renderers/WebGLRenderTargetCube.js
  16727. /**
  16728. * @author alteredq / http://alteredqualia.com
  16729. */
  16730. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16731. THREE.WebGLRenderTarget.call( this, width, height, options );
  16732. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16733. };
  16734. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16735. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16736. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16737. /**
  16738. * @author mrdoob / http://mrdoob.com/
  16739. */
  16740. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16741. var mode;
  16742. function setMode( value ) {
  16743. mode = value;
  16744. }
  16745. function render( start, count ) {
  16746. _gl.drawArrays( mode, start, count );
  16747. _infoRender.calls ++;
  16748. _infoRender.vertices += count;
  16749. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16750. }
  16751. function renderInstances( geometry ) {
  16752. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16753. if ( extension === null ) {
  16754. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16755. return;
  16756. }
  16757. var position = geometry.attributes.position;
  16758. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16759. extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
  16760. } else {
  16761. extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
  16762. }
  16763. }
  16764. this.setMode = setMode;
  16765. this.render = render;
  16766. this.renderInstances = renderInstances;
  16767. };
  16768. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16769. /**
  16770. * @author mrdoob / http://mrdoob.com/
  16771. */
  16772. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16773. var mode;
  16774. function setMode( value ) {
  16775. mode = value;
  16776. }
  16777. var type, size;
  16778. function setIndex( index ) {
  16779. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  16780. type = _gl.UNSIGNED_INT;
  16781. size = 4;
  16782. } else {
  16783. type = _gl.UNSIGNED_SHORT;
  16784. size = 2;
  16785. }
  16786. }
  16787. function render( start, count ) {
  16788. _gl.drawElements( mode, count, type, start * size );
  16789. _infoRender.calls ++;
  16790. _infoRender.vertices += count;
  16791. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16792. }
  16793. function renderInstances( geometry, start, count ) {
  16794. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16795. if ( extension === null ) {
  16796. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16797. return;
  16798. }
  16799. var index = geometry.index;
  16800. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  16801. }
  16802. this.setMode = setMode;
  16803. this.setIndex = setIndex;
  16804. this.render = render;
  16805. this.renderInstances = renderInstances;
  16806. };
  16807. // File:src/renderers/webgl/WebGLExtensions.js
  16808. /**
  16809. * @author mrdoob / http://mrdoob.com/
  16810. */
  16811. THREE.WebGLExtensions = function ( gl ) {
  16812. var extensions = {};
  16813. this.get = function ( name ) {
  16814. if ( extensions[ name ] !== undefined ) {
  16815. return extensions[ name ];
  16816. }
  16817. var extension;
  16818. switch ( name ) {
  16819. case 'EXT_texture_filter_anisotropic':
  16820. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16821. break;
  16822. case 'WEBGL_compressed_texture_s3tc':
  16823. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16824. break;
  16825. case 'WEBGL_compressed_texture_pvrtc':
  16826. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16827. break;
  16828. default:
  16829. extension = gl.getExtension( name );
  16830. }
  16831. if ( extension === null ) {
  16832. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16833. }
  16834. extensions[ name ] = extension;
  16835. return extension;
  16836. };
  16837. };
  16838. // File:src/renderers/webgl/WebGLCapabilities.js
  16839. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  16840. function getMaxPrecision( precision ) {
  16841. if ( precision === 'highp' ) {
  16842. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16843. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16844. return 'highp';
  16845. }
  16846. precision = 'mediump';
  16847. }
  16848. if ( precision === 'mediump' ) {
  16849. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16850. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16851. return 'mediump';
  16852. }
  16853. }
  16854. return 'lowp';
  16855. }
  16856. this.getMaxPrecision = getMaxPrecision;
  16857. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16858. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  16859. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16860. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16861. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16862. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16863. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16864. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16865. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16866. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16867. this.vertexTextures = this.maxVertexTextures > 0;
  16868. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16869. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  16870. var _maxPrecision = getMaxPrecision( this.precision );
  16871. if ( _maxPrecision !== this.precision ) {
  16872. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  16873. this.precision = _maxPrecision;
  16874. }
  16875. if ( this.logarithmicDepthBuffer ) {
  16876. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  16877. }
  16878. };
  16879. // File:src/renderers/webgl/WebGLGeometries.js
  16880. /**
  16881. * @author mrdoob / http://mrdoob.com/
  16882. */
  16883. THREE.WebGLGeometries = function ( gl, properties, info ) {
  16884. var geometries = {};
  16885. function get( object ) {
  16886. var geometry = object.geometry;
  16887. if ( geometries[ geometry.id ] !== undefined ) {
  16888. return geometries[ geometry.id ];
  16889. }
  16890. geometry.addEventListener( 'dispose', onGeometryDispose );
  16891. var buffergeometry;
  16892. if ( geometry instanceof THREE.BufferGeometry ) {
  16893. buffergeometry = geometry;
  16894. } else if ( geometry instanceof THREE.Geometry ) {
  16895. if ( geometry._bufferGeometry === undefined ) {
  16896. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  16897. }
  16898. buffergeometry = geometry._bufferGeometry;
  16899. }
  16900. geometries[ geometry.id ] = buffergeometry;
  16901. info.memory.geometries ++;
  16902. return buffergeometry;
  16903. }
  16904. function onGeometryDispose( event ) {
  16905. var geometry = event.target;
  16906. var buffergeometry = geometries[ geometry.id ];
  16907. if ( buffergeometry.index !== null ) {
  16908. deleteAttribute( buffergeometry.index );
  16909. }
  16910. deleteAttributes( buffergeometry.attributes );
  16911. geometry.removeEventListener( 'dispose', onGeometryDispose );
  16912. delete geometries[ geometry.id ];
  16913. var property = properties.get( geometry );
  16914. if ( property.wireframe ) deleteAttribute( property.wireframe );
  16915. properties.delete( geometry );
  16916. info.memory.geometries --;
  16917. }
  16918. function getAttributeBuffer( attribute ) {
  16919. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16920. return properties.get( attribute.data ).__webglBuffer;
  16921. }
  16922. return properties.get( attribute ).__webglBuffer;
  16923. }
  16924. function deleteAttribute( attribute ) {
  16925. var buffer = getAttributeBuffer( attribute );
  16926. if ( buffer !== undefined ) {
  16927. gl.deleteBuffer( buffer );
  16928. removeAttributeBuffer( attribute );
  16929. }
  16930. }
  16931. function deleteAttributes( attributes ) {
  16932. for ( var name in attributes ) {
  16933. deleteAttribute( attributes[ name ] );
  16934. }
  16935. }
  16936. function removeAttributeBuffer( attribute ) {
  16937. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16938. properties.delete( attribute.data );
  16939. } else {
  16940. properties.delete( attribute );
  16941. }
  16942. }
  16943. this.get = get;
  16944. };
  16945. // File:src/renderers/webgl/WebGLObjects.js
  16946. /**
  16947. * @author mrdoob / http://mrdoob.com/
  16948. */
  16949. THREE.WebGLObjects = function ( gl, properties, info ) {
  16950. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  16951. //
  16952. function update( object ) {
  16953. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  16954. var geometry = geometries.get( object );
  16955. if ( object.geometry instanceof THREE.Geometry ) {
  16956. geometry.updateFromObject( object );
  16957. }
  16958. var index = geometry.index;
  16959. var attributes = geometry.attributes;
  16960. if ( index !== null ) {
  16961. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  16962. }
  16963. for ( var name in attributes ) {
  16964. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  16965. }
  16966. // morph targets
  16967. var morphAttributes = geometry.morphAttributes;
  16968. for ( var name in morphAttributes ) {
  16969. var array = morphAttributes[ name ];
  16970. for ( var i = 0, l = array.length; i < l; i ++ ) {
  16971. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  16972. }
  16973. }
  16974. return geometry;
  16975. }
  16976. function updateAttribute( attribute, bufferType ) {
  16977. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  16978. var attributeProperties = properties.get( data );
  16979. if ( attributeProperties.__webglBuffer === undefined ) {
  16980. createBuffer( attributeProperties, data, bufferType );
  16981. } else if ( attributeProperties.version !== data.version ) {
  16982. updateBuffer( attributeProperties, data, bufferType );
  16983. }
  16984. }
  16985. function createBuffer( attributeProperties, data, bufferType ) {
  16986. attributeProperties.__webglBuffer = gl.createBuffer();
  16987. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16988. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  16989. gl.bufferData( bufferType, data.array, usage );
  16990. attributeProperties.version = data.version;
  16991. }
  16992. function updateBuffer( attributeProperties, data, bufferType ) {
  16993. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16994. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  16995. // Not using update ranges
  16996. gl.bufferSubData( bufferType, 0, data.array );
  16997. } else if ( data.updateRange.count === 0 ) {
  16998. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  16999. } else {
  17000. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  17001. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  17002. data.updateRange.count = 0; // reset range
  17003. }
  17004. attributeProperties.version = data.version;
  17005. }
  17006. function getAttributeBuffer( attribute ) {
  17007. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17008. return properties.get( attribute.data ).__webglBuffer;
  17009. }
  17010. return properties.get( attribute ).__webglBuffer;
  17011. }
  17012. function getWireframeAttribute( geometry ) {
  17013. var property = properties.get( geometry );
  17014. if ( property.wireframe !== undefined ) {
  17015. return property.wireframe;
  17016. }
  17017. var indices = [];
  17018. var index = geometry.index;
  17019. var attributes = geometry.attributes;
  17020. var position = attributes.position;
  17021. // console.time( 'wireframe' );
  17022. if ( index !== null ) {
  17023. var edges = {};
  17024. var array = index.array;
  17025. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  17026. var a = array[ i + 0 ];
  17027. var b = array[ i + 1 ];
  17028. var c = array[ i + 2 ];
  17029. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  17030. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  17031. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  17032. }
  17033. } else {
  17034. var array = attributes.position.array;
  17035. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17036. var a = i + 0;
  17037. var b = i + 1;
  17038. var c = i + 2;
  17039. indices.push( a, b, b, c, c, a );
  17040. }
  17041. }
  17042. // console.timeEnd( 'wireframe' );
  17043. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  17044. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  17045. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  17046. property.wireframe = attribute;
  17047. return attribute;
  17048. }
  17049. function checkEdge( edges, a, b ) {
  17050. if ( a > b ) {
  17051. var tmp = a;
  17052. a = b;
  17053. b = tmp;
  17054. }
  17055. var list = edges[ a ];
  17056. if ( list === undefined ) {
  17057. edges[ a ] = [ b ];
  17058. return true;
  17059. } else if ( list.indexOf( b ) === -1 ) {
  17060. list.push( b );
  17061. return true;
  17062. }
  17063. return false;
  17064. }
  17065. this.getAttributeBuffer = getAttributeBuffer;
  17066. this.getWireframeAttribute = getWireframeAttribute;
  17067. this.update = update;
  17068. };
  17069. // File:src/renderers/webgl/WebGLProgram.js
  17070. THREE.WebGLProgram = ( function () {
  17071. var programIdCount = 0;
  17072. // TODO: Combine the regex
  17073. var structRe = /^([\w\d_]+)\.([\w\d_]+)$/;
  17074. var arrayStructRe = /^([\w\d_]+)\[(\d+)\]\.([\w\d_]+)$/;
  17075. var arrayRe = /^([\w\d_]+)\[0\]$/;
  17076. function generateExtensions( extensions, parameters, rendererExtensions ) {
  17077. extensions = extensions || {};
  17078. var chunks = [
  17079. ( extensions.derivatives || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  17080. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  17081. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  17082. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  17083. ];
  17084. return chunks.filter( filterEmptyLine ).join( '\n' );
  17085. }
  17086. function generateDefines( defines ) {
  17087. var chunks = [];
  17088. for ( var name in defines ) {
  17089. var value = defines[ name ];
  17090. if ( value === false ) continue;
  17091. chunks.push( '#define ' + name + ' ' + value );
  17092. }
  17093. return chunks.join( '\n' );
  17094. }
  17095. function fetchUniformLocations( gl, program, identifiers ) {
  17096. var uniforms = {};
  17097. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  17098. for ( var i = 0; i < n; i ++ ) {
  17099. var info = gl.getActiveUniform( program, i );
  17100. var name = info.name;
  17101. var location = gl.getUniformLocation( program, name );
  17102. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  17103. var matches = structRe.exec(name);
  17104. if( matches ) {
  17105. var structName = matches[1];
  17106. var structProperty = matches[2];
  17107. var uniformsStruct = uniforms[ structName ];
  17108. if( ! uniformsStruct ) {
  17109. uniformsStruct = uniforms[ structName ] = {};
  17110. }
  17111. uniformsStruct[ structProperty ] = location;
  17112. continue;
  17113. }
  17114. matches = arrayStructRe.exec(name);
  17115. if( matches ) {
  17116. var arrayName = matches[1];
  17117. var arrayIndex = matches[2];
  17118. var arrayProperty = matches[3];
  17119. var uniformsArray = uniforms[ arrayName ];
  17120. if( ! uniformsArray ) {
  17121. uniformsArray = uniforms[ arrayName ] = [];
  17122. }
  17123. var uniformsArrayIndex = uniformsArray[ arrayIndex ];
  17124. if( ! uniformsArrayIndex ) {
  17125. uniformsArrayIndex = uniformsArray[ arrayIndex ] = {};
  17126. }
  17127. uniformsArrayIndex[ arrayProperty ] = location;
  17128. continue;
  17129. }
  17130. matches = arrayRe.exec(name)
  17131. if( matches ) {
  17132. var arrayName = matches[1];
  17133. uniforms[ arrayName ] = location;
  17134. continue;
  17135. }
  17136. uniforms[ name ] = location;
  17137. }
  17138. return uniforms;
  17139. }
  17140. function fetchAttributeLocations( gl, program, identifiers ) {
  17141. var attributes = {};
  17142. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17143. for ( var i = 0; i < n; i ++ ) {
  17144. var info = gl.getActiveAttrib( program, i );
  17145. var name = info.name;
  17146. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17147. attributes[ name ] = gl.getAttribLocation( program, name );
  17148. }
  17149. return attributes;
  17150. }
  17151. function filterEmptyLine( string ) {
  17152. return string !== '';
  17153. }
  17154. return function WebGLProgram( renderer, code, material, parameters ) {
  17155. var gl = renderer.context;
  17156. var extensions = material.extensions;
  17157. var defines = material.defines;
  17158. var vertexShader = material.__webglShader.vertexShader;
  17159. var fragmentShader = material.__webglShader.fragmentShader;
  17160. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17161. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17162. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17163. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17164. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17165. }
  17166. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17167. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17168. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17169. if ( parameters.envMap ) {
  17170. switch ( material.envMap.mapping ) {
  17171. case THREE.CubeReflectionMapping:
  17172. case THREE.CubeRefractionMapping:
  17173. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17174. break;
  17175. case THREE.EquirectangularReflectionMapping:
  17176. case THREE.EquirectangularRefractionMapping:
  17177. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17178. break;
  17179. case THREE.SphericalReflectionMapping:
  17180. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17181. break;
  17182. }
  17183. switch ( material.envMap.mapping ) {
  17184. case THREE.CubeRefractionMapping:
  17185. case THREE.EquirectangularRefractionMapping:
  17186. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17187. break;
  17188. }
  17189. switch ( material.combine ) {
  17190. case THREE.MultiplyOperation:
  17191. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17192. break;
  17193. case THREE.MixOperation:
  17194. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17195. break;
  17196. case THREE.AddOperation:
  17197. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17198. break;
  17199. }
  17200. }
  17201. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17202. // console.log( 'building new program ' );
  17203. //
  17204. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17205. var customDefines = generateDefines( defines );
  17206. //
  17207. var program = gl.createProgram();
  17208. var prefixVertex, prefixFragment;
  17209. if ( material instanceof THREE.RawShaderMaterial ) {
  17210. prefixVertex = '';
  17211. prefixFragment = '';
  17212. } else {
  17213. prefixVertex = [
  17214. 'precision ' + parameters.precision + ' float;',
  17215. 'precision ' + parameters.precision + ' int;',
  17216. '#define SHADER_NAME ' + material.__webglShader.name,
  17217. customDefines,
  17218. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17219. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17220. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17221. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17222. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17223. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17224. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17225. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17226. '#define NUM_SHADOWS ' + parameters.numShadows,
  17227. '#define MAX_BONES ' + parameters.maxBones,
  17228. parameters.map ? '#define USE_MAP' : '',
  17229. parameters.envMap ? '#define USE_ENVMAP' : '',
  17230. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17231. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17232. parameters.aoMap ? '#define USE_AOMAP' : '',
  17233. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17234. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17235. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17236. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17237. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17238. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17239. parameters.reflectivityMap ? '#define USE_REFLECTIVITYMAP' : '',
  17240. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17241. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17242. parameters.vertexColors ? '#define USE_COLOR' : '',
  17243. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17244. parameters.skinning ? '#define USE_SKINNING' : '',
  17245. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17246. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17247. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17248. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17249. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17250. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17251. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17252. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17253. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17254. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17255. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17256. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17257. 'uniform mat4 modelMatrix;',
  17258. 'uniform mat4 modelViewMatrix;',
  17259. 'uniform mat4 projectionMatrix;',
  17260. 'uniform mat4 viewMatrix;',
  17261. 'uniform mat3 normalMatrix;',
  17262. 'uniform vec3 cameraPosition;',
  17263. 'attribute vec3 position;',
  17264. 'attribute vec3 normal;',
  17265. 'attribute vec2 uv;',
  17266. '#ifdef USE_COLOR',
  17267. ' attribute vec3 color;',
  17268. '#endif',
  17269. '#ifdef USE_MORPHTARGETS',
  17270. ' attribute vec3 morphTarget0;',
  17271. ' attribute vec3 morphTarget1;',
  17272. ' attribute vec3 morphTarget2;',
  17273. ' attribute vec3 morphTarget3;',
  17274. ' #ifdef USE_MORPHNORMALS',
  17275. ' attribute vec3 morphNormal0;',
  17276. ' attribute vec3 morphNormal1;',
  17277. ' attribute vec3 morphNormal2;',
  17278. ' attribute vec3 morphNormal3;',
  17279. ' #else',
  17280. ' attribute vec3 morphTarget4;',
  17281. ' attribute vec3 morphTarget5;',
  17282. ' attribute vec3 morphTarget6;',
  17283. ' attribute vec3 morphTarget7;',
  17284. ' #endif',
  17285. '#endif',
  17286. '#ifdef USE_SKINNING',
  17287. ' attribute vec4 skinIndex;',
  17288. ' attribute vec4 skinWeight;',
  17289. '#endif',
  17290. '\n'
  17291. ].filter( filterEmptyLine ).join( '\n' );
  17292. prefixFragment = [
  17293. customExtensions,
  17294. 'precision ' + parameters.precision + ' float;',
  17295. 'precision ' + parameters.precision + ' int;',
  17296. '#define SHADER_NAME ' + material.__webglShader.name,
  17297. customDefines,
  17298. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17299. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17300. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17301. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17302. '#define NUM_SHADOWS ' + parameters.numShadows,
  17303. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17304. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17305. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17306. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17307. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17308. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17309. parameters.map ? '#define USE_MAP' : '',
  17310. parameters.envMap ? '#define USE_ENVMAP' : '',
  17311. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17312. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17313. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17314. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17315. parameters.aoMap ? '#define USE_AOMAP' : '',
  17316. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17317. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17318. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17319. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17320. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17321. parameters.reflectivityMap ? '#define USE_REFLECTIVITYMAP' : '',
  17322. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17323. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17324. parameters.vertexColors ? '#define USE_COLOR' : '',
  17325. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17326. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17327. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17328. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17329. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17330. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17331. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17332. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17333. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17334. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_CUBE_LOD_EXT' : '',
  17335. 'uniform mat4 viewMatrix;',
  17336. 'uniform vec3 cameraPosition;',
  17337. '\n'
  17338. ].filter( filterEmptyLine ).join( '\n' );
  17339. }
  17340. var vertexGlsl = prefixVertex + vertexShader;
  17341. var fragmentGlsl = prefixFragment + fragmentShader;
  17342. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17343. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17344. gl.attachShader( program, glVertexShader );
  17345. gl.attachShader( program, glFragmentShader );
  17346. // Force a particular attribute to index 0.
  17347. if ( material.index0AttributeName !== undefined ) {
  17348. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17349. } else if ( parameters.morphTargets === true ) {
  17350. // programs with morphTargets displace position out of attribute 0
  17351. gl.bindAttribLocation( program, 0, 'position' );
  17352. }
  17353. gl.linkProgram( program );
  17354. var programLog = gl.getProgramInfoLog( program );
  17355. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17356. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17357. var runnable = true;
  17358. var haveDiagnostics = true;
  17359. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17360. runnable = false;
  17361. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17362. } else if ( programLog !== '' ) {
  17363. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17364. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17365. haveDiagnostics = false;
  17366. }
  17367. if ( haveDiagnostics ) {
  17368. this.diagnostics = {
  17369. runnable: runnable,
  17370. material: material,
  17371. programLog: programLog,
  17372. vertexShader: {
  17373. log: vertexLog,
  17374. prefix: prefixVertex
  17375. },
  17376. fragmentShader: {
  17377. log: fragmentLog,
  17378. prefix: prefixFragment
  17379. }
  17380. };
  17381. }
  17382. // clean up
  17383. gl.deleteShader( glVertexShader );
  17384. gl.deleteShader( glFragmentShader );
  17385. // set up caching for uniform locations
  17386. var cachedUniforms;
  17387. this.getUniforms = function() {
  17388. if ( cachedUniforms === undefined ) {
  17389. cachedUniforms = fetchUniformLocations( gl, program );
  17390. }
  17391. return cachedUniforms;
  17392. };
  17393. // set up caching for attribute locations
  17394. var cachedAttributes;
  17395. this.getAttributes = function() {
  17396. if ( cachedAttributes === undefined ) {
  17397. cachedAttributes = fetchAttributeLocations( gl, program );
  17398. }
  17399. return cachedAttributes;
  17400. };
  17401. // free resource
  17402. this.destroy = function() {
  17403. gl.deleteProgram( program );
  17404. this.program = undefined;
  17405. };
  17406. // DEPRECATED
  17407. Object.defineProperties( this, {
  17408. uniforms: {
  17409. get: function() {
  17410. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17411. return this.getUniforms();
  17412. }
  17413. },
  17414. attributes: {
  17415. get: function() {
  17416. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17417. return this.getAttributes();
  17418. }
  17419. }
  17420. } );
  17421. //
  17422. this.id = programIdCount ++;
  17423. this.code = code;
  17424. this.usedTimes = 1;
  17425. this.program = program;
  17426. this.vertexShader = glVertexShader;
  17427. this.fragmentShader = glFragmentShader;
  17428. return this;
  17429. };
  17430. } )();
  17431. // File:src/renderers/webgl/WebGLPrograms.js
  17432. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17433. var programs = [];
  17434. var shaderIDs = {
  17435. MeshDepthMaterial: 'depth',
  17436. MeshNormalMaterial: 'normal',
  17437. MeshBasicMaterial: 'basic',
  17438. MeshLambertMaterial: 'lambert',
  17439. MeshPhongMaterial: 'phong',
  17440. MeshStandardMaterial: 'standard',
  17441. LineBasicMaterial: 'basic',
  17442. LineDashedMaterial: 'dashed',
  17443. PointsMaterial: 'points'
  17444. };
  17445. var parameterNames = [
  17446. "precision", "supportsVertexTextures", "map", "envMap", "envMapMode",
  17447. "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17448. "roughnessMap", "reflectivityMap", "metalnessMap",
  17449. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17450. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17451. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17452. "maxMorphTargets", "maxMorphNormals", "numDirLights", "numPointLights",
  17453. "numSpotLights", "numHemiLights", "numShadows", "shadowMapEnabled", "pointLightShadows",
  17454. "shadowMapType", "shadowMapDebug", "alphaTest", "doubleSided",
  17455. "flipSided"
  17456. ];
  17457. function allocateBones ( object ) {
  17458. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17459. return 1024;
  17460. } else {
  17461. // default for when object is not specified
  17462. // ( for example when prebuilding shader to be used with multiple objects )
  17463. //
  17464. // - leave some extra space for other uniforms
  17465. // - limit here is ANGLE's 254 max uniform vectors
  17466. // (up to 54 should be safe)
  17467. var nVertexUniforms = capabilities.maxVertexUniforms;
  17468. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17469. var maxBones = nVertexMatrices;
  17470. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17471. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17472. if ( maxBones < object.skeleton.bones.length ) {
  17473. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17474. }
  17475. }
  17476. return maxBones;
  17477. }
  17478. }
  17479. this.getParameters = function ( material, lights, fog, object ) {
  17480. var shaderID = shaderIDs[ material.type ];
  17481. // heuristics to create shader parameters according to lights in the scene
  17482. // (not to blow over maxLights budget)
  17483. var maxBones = allocateBones( object );
  17484. var precision = renderer.getPrecision();
  17485. if ( material.precision !== null ) {
  17486. precision = capabilities.getMaxPrecision( material.precision );
  17487. if ( precision !== material.precision ) {
  17488. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  17489. }
  17490. }
  17491. var parameters = {
  17492. shaderID: shaderID,
  17493. precision: precision,
  17494. supportsVertexTextures: capabilities.vertexTextures,
  17495. map: !! material.map,
  17496. envMap: !! material.envMap,
  17497. envMapMode: material.envMap && material.envMap.mapping,
  17498. lightMap: !! material.lightMap,
  17499. aoMap: !! material.aoMap,
  17500. emissiveMap: !! material.emissiveMap,
  17501. bumpMap: !! material.bumpMap,
  17502. normalMap: !! material.normalMap,
  17503. displacementMap: !! material.displacementMap,
  17504. roughnessMap: !! material.roughnessMap,
  17505. reflectivityMap: !! material.reflectivityMap,
  17506. metalnessMap: !! material.metalnessMap,
  17507. specularMap: !! material.specularMap,
  17508. alphaMap: !! material.alphaMap,
  17509. combine: material.combine,
  17510. vertexColors: material.vertexColors,
  17511. fog: fog,
  17512. useFog: material.fog,
  17513. fogExp: fog instanceof THREE.FogExp2,
  17514. flatShading: material.shading === THREE.FlatShading,
  17515. sizeAttenuation: material.sizeAttenuation,
  17516. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17517. skinning: material.skinning,
  17518. maxBones: maxBones,
  17519. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17520. morphTargets: material.morphTargets,
  17521. morphNormals: material.morphNormals,
  17522. maxMorphTargets: renderer.maxMorphTargets,
  17523. maxMorphNormals: renderer.maxMorphNormals,
  17524. numDirLights: lights.directional.length,
  17525. numPointLights: lights.point.length,
  17526. numSpotLights: lights.spot.length,
  17527. numHemiLights: lights.hemi.length,
  17528. numShadows: lights.shadows.length,
  17529. pointLightShadows: lights.shadowsPointLight,
  17530. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  17531. shadowMapType: renderer.shadowMap.type,
  17532. shadowMapDebug: renderer.shadowMap.debug,
  17533. alphaTest: material.alphaTest,
  17534. doubleSided: material.side === THREE.DoubleSide,
  17535. flipSided: material.side === THREE.BackSide
  17536. };
  17537. return parameters;
  17538. };
  17539. this.getProgramCode = function ( material, parameters ) {
  17540. var chunks = [];
  17541. if ( parameters.shaderID ) {
  17542. chunks.push( parameters.shaderID );
  17543. } else {
  17544. chunks.push( material.fragmentShader );
  17545. chunks.push( material.vertexShader );
  17546. }
  17547. if ( material.defines !== undefined ) {
  17548. for ( var name in material.defines ) {
  17549. chunks.push( name );
  17550. chunks.push( material.defines[ name ] );
  17551. }
  17552. }
  17553. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17554. var parameterName = parameterNames[ i ];
  17555. chunks.push( parameterName );
  17556. chunks.push( parameters[ parameterName ] );
  17557. }
  17558. return chunks.join();
  17559. };
  17560. this.acquireProgram = function ( material, parameters, code ) {
  17561. var program;
  17562. // Check if code has been already compiled
  17563. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17564. var programInfo = programs[ p ];
  17565. if ( programInfo.code === code ) {
  17566. program = programInfo;
  17567. ++ program.usedTimes;
  17568. break;
  17569. }
  17570. }
  17571. if ( program === undefined ) {
  17572. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17573. programs.push( program );
  17574. }
  17575. return program;
  17576. };
  17577. this.releaseProgram = function( program ) {
  17578. if ( -- program.usedTimes === 0 ) {
  17579. // Remove from unordered set
  17580. var i = programs.indexOf( program );
  17581. programs[ i ] = programs[ programs.length - 1 ];
  17582. programs.pop();
  17583. // Free WebGL resources
  17584. program.destroy();
  17585. }
  17586. };
  17587. // Exposed for resource monitoring & error feedback via renderer.info:
  17588. this.programs = programs;
  17589. };
  17590. // File:src/renderers/webgl/WebGLProperties.js
  17591. /**
  17592. * @author fordacious / fordacious.github.io
  17593. */
  17594. THREE.WebGLProperties = function () {
  17595. var properties = {};
  17596. this.get = function ( object ) {
  17597. var uuid = object.uuid;
  17598. var map = properties[ uuid ];
  17599. if ( map === undefined ) {
  17600. map = {};
  17601. properties[ uuid ] = map;
  17602. }
  17603. return map;
  17604. };
  17605. this.delete = function ( object ) {
  17606. delete properties[ object.uuid ];
  17607. };
  17608. this.clear = function () {
  17609. properties = {};
  17610. };
  17611. };
  17612. // File:src/renderers/webgl/WebGLShader.js
  17613. THREE.WebGLShader = ( function () {
  17614. function addLineNumbers( string ) {
  17615. var lines = string.split( '\n' );
  17616. for ( var i = 0; i < lines.length; i ++ ) {
  17617. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17618. }
  17619. return lines.join( '\n' );
  17620. }
  17621. return function WebGLShader( gl, type, string ) {
  17622. var shader = gl.createShader( type );
  17623. gl.shaderSource( shader, string );
  17624. gl.compileShader( shader );
  17625. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17626. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17627. }
  17628. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17629. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17630. }
  17631. // --enable-privileged-webgl-extension
  17632. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17633. return shader;
  17634. };
  17635. } )();
  17636. // File:src/renderers/webgl/WebGLShadowMap.js
  17637. /**
  17638. * @author alteredq / http://alteredqualia.com/
  17639. * @author mrdoob / http://mrdoob.com/
  17640. */
  17641. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17642. var _gl = _renderer.context,
  17643. _state = _renderer.state,
  17644. _frustum = new THREE.Frustum(),
  17645. _projScreenMatrix = new THREE.Matrix4(),
  17646. _min = new THREE.Vector3(),
  17647. _max = new THREE.Vector3(),
  17648. _lookTarget = new THREE.Vector3(),
  17649. _lightPositionWorld = new THREE.Vector3(),
  17650. _renderList = [],
  17651. _MorphingFlag = 1,
  17652. _SkinningFlag = 2,
  17653. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17654. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17655. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  17656. var cubeDirections = [
  17657. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17658. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17659. ];
  17660. var cubeUps = [
  17661. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17662. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17663. ];
  17664. var cube2DViewPorts = [
  17665. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17666. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17667. ];
  17668. var _vector4 = new THREE.Vector4();
  17669. // init
  17670. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  17671. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  17672. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17673. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17674. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17675. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17676. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17677. var depthMaterial = new THREE.ShaderMaterial( {
  17678. uniforms: depthUniforms,
  17679. vertexShader: depthShader.vertexShader,
  17680. fragmentShader: depthShader.fragmentShader,
  17681. morphTargets: useMorphing,
  17682. skinning: useSkinning
  17683. } );
  17684. depthMaterial._shadowPass = true;
  17685. _depthMaterials[ i ] = depthMaterial;
  17686. var distanceMaterial = new THREE.ShaderMaterial( {
  17687. uniforms: distanceUniforms,
  17688. vertexShader: distanceShader.vertexShader,
  17689. fragmentShader: distanceShader.fragmentShader,
  17690. morphTargets: useMorphing,
  17691. skinning: useSkinning
  17692. } );
  17693. distanceMaterial._shadowPass = true;
  17694. _distanceMaterials[ i ] = distanceMaterial;
  17695. }
  17696. //
  17697. var scope = this;
  17698. this.enabled = false;
  17699. this.autoUpdate = true;
  17700. this.needsUpdate = false;
  17701. this.type = THREE.PCFShadowMap;
  17702. this.cullFace = THREE.CullFaceFront;
  17703. this.render = function ( scene, camera ) {
  17704. var faceCount, isPointLight;
  17705. if ( scope.enabled === false ) return;
  17706. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17707. // Set GL state for depth map.
  17708. _gl.clearColor( 1, 1, 1, 1 );
  17709. _state.disable( _gl.BLEND );
  17710. _state.enable( _gl.CULL_FACE );
  17711. _gl.frontFace( _gl.CCW );
  17712. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17713. _state.setDepthTest( true );
  17714. // save the existing viewport so it can be restored later
  17715. _renderer.getViewport( _vector4 );
  17716. // render depth map
  17717. var shadows = _lights.shadows;
  17718. for ( var i = 0, il = shadows.length; i < il; i ++ ) {
  17719. var light = shadows[ i ];
  17720. var shadow = light.shadow;
  17721. var shadowCamera = shadow.camera;
  17722. var shadowMapSize = shadow.mapSize;
  17723. if ( light instanceof THREE.PointLight ) {
  17724. faceCount = 6;
  17725. isPointLight = true;
  17726. var vpWidth = shadowMapSize.x / 4.0;
  17727. var vpHeight = shadowMapSize.y / 2.0;
  17728. // These viewports map a cube-map onto a 2D texture with the
  17729. // following orientation:
  17730. //
  17731. // xzXZ
  17732. // y Y
  17733. //
  17734. // X - Positive x direction
  17735. // x - Negative x direction
  17736. // Y - Positive y direction
  17737. // y - Negative y direction
  17738. // Z - Positive z direction
  17739. // z - Negative z direction
  17740. // positive X
  17741. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  17742. // negative X
  17743. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  17744. // positive Z
  17745. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  17746. // negative Z
  17747. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  17748. // positive Y
  17749. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  17750. // negative Y
  17751. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  17752. } else {
  17753. faceCount = 1;
  17754. isPointLight = false;
  17755. }
  17756. if ( shadow.map === null ) {
  17757. var shadowFilter = THREE.LinearFilter;
  17758. if ( scope.type === THREE.PCFSoftShadowMap ) {
  17759. shadowFilter = THREE.NearestFilter;
  17760. }
  17761. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  17762. shadow.map = new THREE.WebGLRenderTarget( shadowMapSize.x, shadowMapSize.y, pars );
  17763. shadow.matrix = new THREE.Matrix4();
  17764. //
  17765. if ( light instanceof THREE.SpotLight ) {
  17766. shadowCamera.aspect = shadowMapSize.x / shadowMapSize.y;
  17767. }
  17768. shadowCamera.updateProjectionMatrix();
  17769. }
  17770. var shadowMap = shadow.map;
  17771. var shadowMatrix = shadow.matrix;
  17772. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  17773. shadowCamera.position.copy( _lightPositionWorld );
  17774. _renderer.setRenderTarget( shadowMap );
  17775. _renderer.clear();
  17776. // render shadow map for each cube face (if omni-directional) or
  17777. // run a single pass if not
  17778. for ( var face = 0; face < faceCount; face ++ ) {
  17779. if ( isPointLight ) {
  17780. _lookTarget.copy( shadowCamera.position );
  17781. _lookTarget.add( cubeDirections[ face ] );
  17782. shadowCamera.up.copy( cubeUps[ face ] );
  17783. shadowCamera.lookAt( _lookTarget );
  17784. var vpDimensions = cube2DViewPorts[ face ];
  17785. _renderer.setViewport( vpDimensions.x, vpDimensions.y, vpDimensions.z, vpDimensions.w );
  17786. } else {
  17787. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  17788. shadowCamera.lookAt( _lookTarget );
  17789. }
  17790. shadowCamera.updateMatrixWorld();
  17791. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  17792. // compute shadow matrix
  17793. shadowMatrix.set(
  17794. 0.5, 0.0, 0.0, 0.5,
  17795. 0.0, 0.5, 0.0, 0.5,
  17796. 0.0, 0.0, 0.5, 0.5,
  17797. 0.0, 0.0, 0.0, 1.0
  17798. );
  17799. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  17800. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  17801. // update camera matrices and frustum
  17802. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  17803. _frustum.setFromMatrix( _projScreenMatrix );
  17804. // set object matrices & frustum culling
  17805. _renderList.length = 0;
  17806. projectObject( scene, camera, shadowCamera );
  17807. // render shadow map
  17808. // render regular objects
  17809. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  17810. var object = _renderList[ j ];
  17811. var geometry = _objects.update( object );
  17812. var material = object.material;
  17813. if ( material instanceof THREE.MeshFaceMaterial ) {
  17814. var groups = geometry.groups;
  17815. var materials = material.materials;
  17816. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17817. var group = groups[ k ];
  17818. var groupMaterial = materials[ group.materialIndex ];
  17819. if ( groupMaterial.visible === true ) {
  17820. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  17821. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17822. }
  17823. }
  17824. } else {
  17825. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  17826. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17827. }
  17828. }
  17829. }
  17830. // We must call _renderer.resetGLState() at the end of each iteration of
  17831. // the light loop in order to force material updates for each light.
  17832. _renderer.resetGLState();
  17833. }
  17834. _renderer.setViewport( _vector4.x, _vector4.y, _vector4.z, _vector4.w );
  17835. // Restore GL state.
  17836. var clearColor = _renderer.getClearColor(),
  17837. clearAlpha = _renderer.getClearAlpha();
  17838. _renderer.setClearColor( clearColor, clearAlpha );
  17839. _state.enable( _gl.BLEND );
  17840. if ( scope.cullFace === THREE.CullFaceFront ) {
  17841. _gl.cullFace( _gl.BACK );
  17842. }
  17843. _renderer.resetGLState();
  17844. scope.needsUpdate = false;
  17845. };
  17846. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  17847. var geometry = object.geometry;
  17848. var newMaterial = null;
  17849. var materialVariants = _depthMaterials;
  17850. var customMaterial = object.customDepthMaterial;
  17851. if ( isPointLight ) {
  17852. materialVariants = _distanceMaterials;
  17853. customMaterial = object.customDistanceMaterial;
  17854. }
  17855. if ( ! customMaterial ) {
  17856. var useMorphing = geometry.morphTargets !== undefined &&
  17857. geometry.morphTargets.length > 0 && material.morphTargets;
  17858. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  17859. var variantIndex = 0;
  17860. if ( useMorphing ) variantIndex |= _MorphingFlag;
  17861. if ( useSkinning ) variantIndex |= _SkinningFlag;
  17862. newMaterial = materialVariants[ variantIndex ];
  17863. } else {
  17864. newMaterial = customMaterial;
  17865. }
  17866. newMaterial.visible = material.visible;
  17867. newMaterial.wireframe = material.wireframe;
  17868. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  17869. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  17870. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  17871. }
  17872. return newMaterial;
  17873. }
  17874. function projectObject( object, camera, shadowCamera ) {
  17875. if ( object.visible === false ) return;
  17876. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  17877. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  17878. var material = object.material;
  17879. if ( material.visible === true ) {
  17880. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17881. _renderList.push( object );
  17882. }
  17883. }
  17884. }
  17885. var children = object.children;
  17886. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17887. projectObject( children[ i ], camera, shadowCamera );
  17888. }
  17889. }
  17890. };
  17891. // File:src/renderers/webgl/WebGLState.js
  17892. /**
  17893. * @author mrdoob / http://mrdoob.com/
  17894. */
  17895. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  17896. var _this = this;
  17897. var newAttributes = new Uint8Array( 16 );
  17898. var enabledAttributes = new Uint8Array( 16 );
  17899. var attributeDivisors = new Uint8Array( 16 );
  17900. var capabilities = {};
  17901. var compressedTextureFormats = null;
  17902. var currentBlending = null;
  17903. var currentBlendEquation = null;
  17904. var currentBlendSrc = null;
  17905. var currentBlendDst = null;
  17906. var currentBlendEquationAlpha = null;
  17907. var currentBlendSrcAlpha = null;
  17908. var currentBlendDstAlpha = null;
  17909. var currentDepthFunc = null;
  17910. var currentDepthWrite = null;
  17911. var currentColorWrite = null;
  17912. var currentFlipSided = null;
  17913. var currentLineWidth = null;
  17914. var currentPolygonOffsetFactor = null;
  17915. var currentPolygonOffsetUnits = null;
  17916. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  17917. var currentTextureSlot = undefined;
  17918. var currentBoundTextures = {};
  17919. this.init = function () {
  17920. gl.clearColor( 0, 0, 0, 1 );
  17921. gl.clearDepth( 1 );
  17922. gl.clearStencil( 0 );
  17923. this.enable( gl.DEPTH_TEST );
  17924. gl.depthFunc( gl.LEQUAL );
  17925. gl.frontFace( gl.CCW );
  17926. gl.cullFace( gl.BACK );
  17927. this.enable( gl.CULL_FACE );
  17928. this.enable( gl.BLEND );
  17929. gl.blendEquation( gl.FUNC_ADD );
  17930. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  17931. };
  17932. this.initAttributes = function () {
  17933. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  17934. newAttributes[ i ] = 0;
  17935. }
  17936. };
  17937. this.enableAttribute = function ( attribute ) {
  17938. newAttributes[ attribute ] = 1;
  17939. if ( enabledAttributes[ attribute ] === 0 ) {
  17940. gl.enableVertexAttribArray( attribute );
  17941. enabledAttributes[ attribute ] = 1;
  17942. }
  17943. if ( attributeDivisors[ attribute ] !== 0 ) {
  17944. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  17945. extension.vertexAttribDivisorANGLE( attribute, 0 );
  17946. attributeDivisors[ attribute ] = 0;
  17947. }
  17948. };
  17949. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  17950. newAttributes[ attribute ] = 1;
  17951. if ( enabledAttributes[ attribute ] === 0 ) {
  17952. gl.enableVertexAttribArray( attribute );
  17953. enabledAttributes[ attribute ] = 1;
  17954. }
  17955. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  17956. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  17957. attributeDivisors[ attribute ] = meshPerAttribute;
  17958. }
  17959. };
  17960. this.disableUnusedAttributes = function () {
  17961. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  17962. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  17963. gl.disableVertexAttribArray( i );
  17964. enabledAttributes[ i ] = 0;
  17965. }
  17966. }
  17967. };
  17968. this.enable = function ( id ) {
  17969. if ( capabilities[ id ] !== true ) {
  17970. gl.enable( id );
  17971. capabilities[ id ] = true;
  17972. }
  17973. };
  17974. this.disable = function ( id ) {
  17975. if ( capabilities[ id ] !== false ) {
  17976. gl.disable( id );
  17977. capabilities[ id ] = false;
  17978. }
  17979. };
  17980. this.getCompressedTextureFormats = function () {
  17981. if ( compressedTextureFormats === null ) {
  17982. compressedTextureFormats = [];
  17983. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  17984. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  17985. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  17986. for ( var i = 0; i < formats.length; i ++ ) {
  17987. compressedTextureFormats.push( formats[ i ] );
  17988. }
  17989. }
  17990. }
  17991. return compressedTextureFormats;
  17992. };
  17993. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  17994. if ( blending !== currentBlending ) {
  17995. if ( blending === THREE.NoBlending ) {
  17996. this.disable( gl.BLEND );
  17997. } else if ( blending === THREE.AdditiveBlending ) {
  17998. this.enable( gl.BLEND );
  17999. gl.blendEquation( gl.FUNC_ADD );
  18000. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18001. } else if ( blending === THREE.SubtractiveBlending ) {
  18002. // TODO: Find blendFuncSeparate() combination
  18003. this.enable( gl.BLEND );
  18004. gl.blendEquation( gl.FUNC_ADD );
  18005. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  18006. } else if ( blending === THREE.MultiplyBlending ) {
  18007. // TODO: Find blendFuncSeparate() combination
  18008. this.enable( gl.BLEND );
  18009. gl.blendEquation( gl.FUNC_ADD );
  18010. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18011. } else if ( blending === THREE.CustomBlending ) {
  18012. this.enable( gl.BLEND );
  18013. } else {
  18014. this.enable( gl.BLEND );
  18015. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18016. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18017. }
  18018. currentBlending = blending;
  18019. }
  18020. if ( blending === THREE.CustomBlending ) {
  18021. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18022. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18023. blendDstAlpha = blendDstAlpha || blendDst;
  18024. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18025. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  18026. currentBlendEquation = blendEquation;
  18027. currentBlendEquationAlpha = blendEquationAlpha;
  18028. }
  18029. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18030. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  18031. currentBlendSrc = blendSrc;
  18032. currentBlendDst = blendDst;
  18033. currentBlendSrcAlpha = blendSrcAlpha;
  18034. currentBlendDstAlpha = blendDstAlpha;
  18035. }
  18036. } else {
  18037. currentBlendEquation = null;
  18038. currentBlendSrc = null;
  18039. currentBlendDst = null;
  18040. currentBlendEquationAlpha = null;
  18041. currentBlendSrcAlpha = null;
  18042. currentBlendDstAlpha = null;
  18043. }
  18044. };
  18045. this.setDepthFunc = function ( depthFunc ) {
  18046. if ( currentDepthFunc !== depthFunc ) {
  18047. if ( depthFunc ) {
  18048. switch ( depthFunc ) {
  18049. case THREE.NeverDepth:
  18050. gl.depthFunc( gl.NEVER );
  18051. break;
  18052. case THREE.AlwaysDepth:
  18053. gl.depthFunc( gl.ALWAYS );
  18054. break;
  18055. case THREE.LessDepth:
  18056. gl.depthFunc( gl.LESS );
  18057. break;
  18058. case THREE.LessEqualDepth:
  18059. gl.depthFunc( gl.LEQUAL );
  18060. break;
  18061. case THREE.EqualDepth:
  18062. gl.depthFunc( gl.EQUAL );
  18063. break;
  18064. case THREE.GreaterEqualDepth:
  18065. gl.depthFunc( gl.GEQUAL );
  18066. break;
  18067. case THREE.GreaterDepth:
  18068. gl.depthFunc( gl.GREATER );
  18069. break;
  18070. case THREE.NotEqualDepth:
  18071. gl.depthFunc( gl.NOTEQUAL );
  18072. break;
  18073. default:
  18074. gl.depthFunc( gl.LEQUAL );
  18075. }
  18076. } else {
  18077. gl.depthFunc( gl.LEQUAL );
  18078. }
  18079. currentDepthFunc = depthFunc;
  18080. }
  18081. };
  18082. this.setDepthTest = function ( depthTest ) {
  18083. if ( depthTest ) {
  18084. this.enable( gl.DEPTH_TEST );
  18085. } else {
  18086. this.disable( gl.DEPTH_TEST );
  18087. }
  18088. };
  18089. this.setDepthWrite = function ( depthWrite ) {
  18090. if ( currentDepthWrite !== depthWrite ) {
  18091. gl.depthMask( depthWrite );
  18092. currentDepthWrite = depthWrite;
  18093. }
  18094. };
  18095. this.setColorWrite = function ( colorWrite ) {
  18096. if ( currentColorWrite !== colorWrite ) {
  18097. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18098. currentColorWrite = colorWrite;
  18099. }
  18100. };
  18101. this.setFlipSided = function ( flipSided ) {
  18102. if ( currentFlipSided !== flipSided ) {
  18103. if ( flipSided ) {
  18104. gl.frontFace( gl.CW );
  18105. } else {
  18106. gl.frontFace( gl.CCW );
  18107. }
  18108. currentFlipSided = flipSided;
  18109. }
  18110. };
  18111. this.setLineWidth = function ( width ) {
  18112. if ( width !== currentLineWidth ) {
  18113. gl.lineWidth( width );
  18114. currentLineWidth = width;
  18115. }
  18116. };
  18117. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18118. if ( polygonOffset ) {
  18119. this.enable( gl.POLYGON_OFFSET_FILL );
  18120. } else {
  18121. this.disable( gl.POLYGON_OFFSET_FILL );
  18122. }
  18123. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18124. gl.polygonOffset( factor, units );
  18125. currentPolygonOffsetFactor = factor;
  18126. currentPolygonOffsetUnits = units;
  18127. }
  18128. };
  18129. this.setScissorTest = function ( scissorTest ) {
  18130. if ( scissorTest ) {
  18131. this.enable( gl.SCISSOR_TEST );
  18132. } else {
  18133. this.disable( gl.SCISSOR_TEST );
  18134. }
  18135. };
  18136. // texture
  18137. this.activeTexture = function ( webglSlot ) {
  18138. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18139. if ( currentTextureSlot !== webglSlot ) {
  18140. gl.activeTexture( webglSlot );
  18141. currentTextureSlot = webglSlot;
  18142. }
  18143. }
  18144. this.bindTexture = function ( webglType, webglTexture ) {
  18145. if ( currentTextureSlot === undefined ) {
  18146. _this.activeTexture();
  18147. }
  18148. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18149. if ( boundTexture === undefined ) {
  18150. boundTexture = { type: undefined, texture: undefined };
  18151. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18152. }
  18153. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18154. gl.bindTexture( webglType, webglTexture );
  18155. boundTexture.type = webglType;
  18156. boundTexture.texture = webglTexture;
  18157. }
  18158. };
  18159. this.compressedTexImage2D = function () {
  18160. try {
  18161. gl.compressedTexImage2D.apply( gl, arguments );
  18162. } catch ( error ) {
  18163. console.error( error );
  18164. }
  18165. };
  18166. this.texImage2D = function () {
  18167. try {
  18168. gl.texImage2D.apply( gl, arguments );
  18169. } catch ( error ) {
  18170. console.error( error );
  18171. }
  18172. };
  18173. //
  18174. this.reset = function () {
  18175. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18176. if ( enabledAttributes[ i ] === 1 ) {
  18177. gl.disableVertexAttribArray( i );
  18178. enabledAttributes[ i ] = 0;
  18179. }
  18180. }
  18181. capabilities = {};
  18182. compressedTextureFormats = null;
  18183. currentBlending = null;
  18184. currentDepthWrite = null;
  18185. currentColorWrite = null;
  18186. currentFlipSided = null;
  18187. };
  18188. };
  18189. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18190. /**
  18191. * @author mikael emtinger / http://gomo.se/
  18192. * @author alteredq / http://alteredqualia.com/
  18193. */
  18194. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18195. var gl = renderer.context;
  18196. var state = renderer.state;
  18197. var vertexBuffer, elementBuffer;
  18198. var program, attributes, uniforms;
  18199. var hasVertexTexture;
  18200. var tempTexture, occlusionTexture;
  18201. function init() {
  18202. var vertices = new Float32Array( [
  18203. - 1, - 1, 0, 0,
  18204. 1, - 1, 1, 0,
  18205. 1, 1, 1, 1,
  18206. - 1, 1, 0, 1
  18207. ] );
  18208. var faces = new Uint16Array( [
  18209. 0, 1, 2,
  18210. 0, 2, 3
  18211. ] );
  18212. // buffers
  18213. vertexBuffer = gl.createBuffer();
  18214. elementBuffer = gl.createBuffer();
  18215. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18216. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18217. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18218. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18219. // textures
  18220. tempTexture = gl.createTexture();
  18221. occlusionTexture = gl.createTexture();
  18222. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18223. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18224. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18225. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18226. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18227. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18228. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18229. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18230. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18231. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18232. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18233. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18234. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  18235. var shader;
  18236. if ( hasVertexTexture ) {
  18237. shader = {
  18238. vertexShader: [
  18239. "uniform lowp int renderType;",
  18240. "uniform vec3 screenPosition;",
  18241. "uniform vec2 scale;",
  18242. "uniform float rotation;",
  18243. "uniform sampler2D occlusionMap;",
  18244. "attribute vec2 position;",
  18245. "attribute vec2 uv;",
  18246. "varying vec2 vUV;",
  18247. "varying float vVisibility;",
  18248. "void main() {",
  18249. "vUV = uv;",
  18250. "vec2 pos = position;",
  18251. "if ( renderType == 2 ) {",
  18252. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18253. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18254. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18255. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18256. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18257. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18258. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18259. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18260. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18261. "vVisibility = visibility.r / 9.0;",
  18262. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18263. "vVisibility *= visibility.b / 9.0;",
  18264. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18265. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18266. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18267. "}",
  18268. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18269. "}"
  18270. ].join( "\n" ),
  18271. fragmentShader: [
  18272. "uniform lowp int renderType;",
  18273. "uniform sampler2D map;",
  18274. "uniform float opacity;",
  18275. "uniform vec3 color;",
  18276. "varying vec2 vUV;",
  18277. "varying float vVisibility;",
  18278. "void main() {",
  18279. // pink square
  18280. "if ( renderType == 0 ) {",
  18281. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18282. // restore
  18283. "} else if ( renderType == 1 ) {",
  18284. "gl_FragColor = texture2D( map, vUV );",
  18285. // flare
  18286. "} else {",
  18287. "vec4 texture = texture2D( map, vUV );",
  18288. "texture.a *= opacity * vVisibility;",
  18289. "gl_FragColor = texture;",
  18290. "gl_FragColor.rgb *= color;",
  18291. "}",
  18292. "}"
  18293. ].join( "\n" )
  18294. };
  18295. } else {
  18296. shader = {
  18297. vertexShader: [
  18298. "uniform lowp int renderType;",
  18299. "uniform vec3 screenPosition;",
  18300. "uniform vec2 scale;",
  18301. "uniform float rotation;",
  18302. "attribute vec2 position;",
  18303. "attribute vec2 uv;",
  18304. "varying vec2 vUV;",
  18305. "void main() {",
  18306. "vUV = uv;",
  18307. "vec2 pos = position;",
  18308. "if ( renderType == 2 ) {",
  18309. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18310. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18311. "}",
  18312. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18313. "}"
  18314. ].join( "\n" ),
  18315. fragmentShader: [
  18316. "precision mediump float;",
  18317. "uniform lowp int renderType;",
  18318. "uniform sampler2D map;",
  18319. "uniform sampler2D occlusionMap;",
  18320. "uniform float opacity;",
  18321. "uniform vec3 color;",
  18322. "varying vec2 vUV;",
  18323. "void main() {",
  18324. // pink square
  18325. "if ( renderType == 0 ) {",
  18326. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  18327. // restore
  18328. "} else if ( renderType == 1 ) {",
  18329. "gl_FragColor = texture2D( map, vUV );",
  18330. // flare
  18331. "} else {",
  18332. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  18333. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  18334. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  18335. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  18336. "visibility = ( 1.0 - visibility / 4.0 );",
  18337. "vec4 texture = texture2D( map, vUV );",
  18338. "texture.a *= opacity * visibility;",
  18339. "gl_FragColor = texture;",
  18340. "gl_FragColor.rgb *= color;",
  18341. "}",
  18342. "}"
  18343. ].join( "\n" )
  18344. };
  18345. }
  18346. program = createProgram( shader );
  18347. attributes = {
  18348. vertex: gl.getAttribLocation ( program, "position" ),
  18349. uv: gl.getAttribLocation ( program, "uv" )
  18350. };
  18351. uniforms = {
  18352. renderType: gl.getUniformLocation( program, "renderType" ),
  18353. map: gl.getUniformLocation( program, "map" ),
  18354. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18355. opacity: gl.getUniformLocation( program, "opacity" ),
  18356. color: gl.getUniformLocation( program, "color" ),
  18357. scale: gl.getUniformLocation( program, "scale" ),
  18358. rotation: gl.getUniformLocation( program, "rotation" ),
  18359. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18360. };
  18361. }
  18362. /*
  18363. * Render lens flares
  18364. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18365. * reads these back and calculates occlusion.
  18366. */
  18367. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  18368. if ( flares.length === 0 ) return;
  18369. var tempPosition = new THREE.Vector3();
  18370. var invAspect = viewportHeight / viewportWidth,
  18371. halfViewportWidth = viewportWidth * 0.5,
  18372. halfViewportHeight = viewportHeight * 0.5;
  18373. var size = 16 / viewportHeight,
  18374. scale = new THREE.Vector2( size * invAspect, size );
  18375. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18376. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18377. if ( program === undefined ) {
  18378. init();
  18379. }
  18380. gl.useProgram( program );
  18381. state.initAttributes();
  18382. state.enableAttribute( attributes.vertex );
  18383. state.enableAttribute( attributes.uv );
  18384. state.disableUnusedAttributes();
  18385. // loop through all lens flares to update their occlusion and positions
  18386. // setup gl and common used attribs/uniforms
  18387. gl.uniform1i( uniforms.occlusionMap, 0 );
  18388. gl.uniform1i( uniforms.map, 1 );
  18389. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18390. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18391. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18392. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18393. state.disable( gl.CULL_FACE );
  18394. gl.depthMask( false );
  18395. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18396. size = 16 / viewportHeight;
  18397. scale.set( size * invAspect, size );
  18398. // calc object screen position
  18399. var flare = flares[ i ];
  18400. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18401. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18402. tempPosition.applyProjection( camera.projectionMatrix );
  18403. // setup arrays for gl programs
  18404. screenPosition.copy( tempPosition );
  18405. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  18406. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  18407. // screen cull
  18408. if ( hasVertexTexture || (
  18409. screenPositionPixels.x > 0 &&
  18410. screenPositionPixels.x < viewportWidth &&
  18411. screenPositionPixels.y > 0 &&
  18412. screenPositionPixels.y < viewportHeight ) ) {
  18413. // save current RGB to temp texture
  18414. state.activeTexture( gl.TEXTURE0 );
  18415. state.bindTexture( gl.TEXTURE_2D, null );
  18416. state.activeTexture( gl.TEXTURE1 );
  18417. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18418. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18419. // render pink quad
  18420. gl.uniform1i( uniforms.renderType, 0 );
  18421. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18422. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18423. state.disable( gl.BLEND );
  18424. state.enable( gl.DEPTH_TEST );
  18425. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18426. // copy result to occlusionMap
  18427. state.activeTexture( gl.TEXTURE0 );
  18428. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18429. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18430. // restore graphics
  18431. gl.uniform1i( uniforms.renderType, 1 );
  18432. state.disable( gl.DEPTH_TEST );
  18433. state.activeTexture( gl.TEXTURE1 );
  18434. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18435. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18436. // update object positions
  18437. flare.positionScreen.copy( screenPosition );
  18438. if ( flare.customUpdateCallback ) {
  18439. flare.customUpdateCallback( flare );
  18440. } else {
  18441. flare.updateLensFlares();
  18442. }
  18443. // render flares
  18444. gl.uniform1i( uniforms.renderType, 2 );
  18445. state.enable( gl.BLEND );
  18446. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  18447. var sprite = flare.lensFlares[ j ];
  18448. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  18449. screenPosition.x = sprite.x;
  18450. screenPosition.y = sprite.y;
  18451. screenPosition.z = sprite.z;
  18452. size = sprite.size * sprite.scale / viewportHeight;
  18453. scale.x = size * invAspect;
  18454. scale.y = size;
  18455. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18456. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18457. gl.uniform1f( uniforms.rotation, sprite.rotation );
  18458. gl.uniform1f( uniforms.opacity, sprite.opacity );
  18459. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  18460. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  18461. renderer.setTexture( sprite.texture, 1 );
  18462. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18463. }
  18464. }
  18465. }
  18466. }
  18467. // restore gl
  18468. state.enable( gl.CULL_FACE );
  18469. state.enable( gl.DEPTH_TEST );
  18470. gl.depthMask( true );
  18471. renderer.resetGLState();
  18472. };
  18473. function createProgram ( shader ) {
  18474. var program = gl.createProgram();
  18475. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18476. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18477. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  18478. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  18479. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  18480. gl.compileShader( fragmentShader );
  18481. gl.compileShader( vertexShader );
  18482. gl.attachShader( program, fragmentShader );
  18483. gl.attachShader( program, vertexShader );
  18484. gl.linkProgram( program );
  18485. return program;
  18486. }
  18487. };
  18488. // File:src/renderers/webgl/plugins/SpritePlugin.js
  18489. /**
  18490. * @author mikael emtinger / http://gomo.se/
  18491. * @author alteredq / http://alteredqualia.com/
  18492. */
  18493. THREE.SpritePlugin = function ( renderer, sprites ) {
  18494. var gl = renderer.context;
  18495. var state = renderer.state;
  18496. var vertexBuffer, elementBuffer;
  18497. var program, attributes, uniforms;
  18498. var texture;
  18499. // decompose matrixWorld
  18500. var spritePosition = new THREE.Vector3();
  18501. var spriteRotation = new THREE.Quaternion();
  18502. var spriteScale = new THREE.Vector3();
  18503. function init() {
  18504. var vertices = new Float32Array( [
  18505. - 0.5, - 0.5, 0, 0,
  18506. 0.5, - 0.5, 1, 0,
  18507. 0.5, 0.5, 1, 1,
  18508. - 0.5, 0.5, 0, 1
  18509. ] );
  18510. var faces = new Uint16Array( [
  18511. 0, 1, 2,
  18512. 0, 2, 3
  18513. ] );
  18514. vertexBuffer = gl.createBuffer();
  18515. elementBuffer = gl.createBuffer();
  18516. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18517. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18518. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18519. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18520. program = createProgram();
  18521. attributes = {
  18522. position: gl.getAttribLocation ( program, 'position' ),
  18523. uv: gl.getAttribLocation ( program, 'uv' )
  18524. };
  18525. uniforms = {
  18526. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  18527. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  18528. rotation: gl.getUniformLocation( program, 'rotation' ),
  18529. scale: gl.getUniformLocation( program, 'scale' ),
  18530. color: gl.getUniformLocation( program, 'color' ),
  18531. map: gl.getUniformLocation( program, 'map' ),
  18532. opacity: gl.getUniformLocation( program, 'opacity' ),
  18533. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  18534. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  18535. fogType: gl.getUniformLocation( program, 'fogType' ),
  18536. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  18537. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  18538. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  18539. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  18540. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  18541. };
  18542. var canvas = document.createElement( 'canvas' );
  18543. canvas.width = 8;
  18544. canvas.height = 8;
  18545. var context = canvas.getContext( '2d' );
  18546. context.fillStyle = 'white';
  18547. context.fillRect( 0, 0, 8, 8 );
  18548. texture = new THREE.Texture( canvas );
  18549. texture.needsUpdate = true;
  18550. }
  18551. this.render = function ( scene, camera ) {
  18552. if ( sprites.length === 0 ) return;
  18553. // setup gl
  18554. if ( program === undefined ) {
  18555. init();
  18556. }
  18557. gl.useProgram( program );
  18558. state.initAttributes();
  18559. state.enableAttribute( attributes.position );
  18560. state.enableAttribute( attributes.uv );
  18561. state.disableUnusedAttributes();
  18562. state.disable( gl.CULL_FACE );
  18563. state.enable( gl.BLEND );
  18564. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18565. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  18566. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18567. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18568. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  18569. state.activeTexture( gl.TEXTURE0 );
  18570. gl.uniform1i( uniforms.map, 0 );
  18571. var oldFogType = 0;
  18572. var sceneFogType = 0;
  18573. var fog = scene.fog;
  18574. if ( fog ) {
  18575. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  18576. if ( fog instanceof THREE.Fog ) {
  18577. gl.uniform1f( uniforms.fogNear, fog.near );
  18578. gl.uniform1f( uniforms.fogFar, fog.far );
  18579. gl.uniform1i( uniforms.fogType, 1 );
  18580. oldFogType = 1;
  18581. sceneFogType = 1;
  18582. } else if ( fog instanceof THREE.FogExp2 ) {
  18583. gl.uniform1f( uniforms.fogDensity, fog.density );
  18584. gl.uniform1i( uniforms.fogType, 2 );
  18585. oldFogType = 2;
  18586. sceneFogType = 2;
  18587. }
  18588. } else {
  18589. gl.uniform1i( uniforms.fogType, 0 );
  18590. oldFogType = 0;
  18591. sceneFogType = 0;
  18592. }
  18593. // update positions and sort
  18594. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18595. var sprite = sprites[ i ];
  18596. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  18597. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  18598. }
  18599. sprites.sort( painterSortStable );
  18600. // render all sprites
  18601. var scale = [];
  18602. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18603. var sprite = sprites[ i ];
  18604. var material = sprite.material;
  18605. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  18606. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  18607. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  18608. scale[ 0 ] = spriteScale.x;
  18609. scale[ 1 ] = spriteScale.y;
  18610. var fogType = 0;
  18611. if ( scene.fog && material.fog ) {
  18612. fogType = sceneFogType;
  18613. }
  18614. if ( oldFogType !== fogType ) {
  18615. gl.uniform1i( uniforms.fogType, fogType );
  18616. oldFogType = fogType;
  18617. }
  18618. if ( material.map !== null ) {
  18619. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  18620. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  18621. } else {
  18622. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  18623. gl.uniform2f( uniforms.uvScale, 1, 1 );
  18624. }
  18625. gl.uniform1f( uniforms.opacity, material.opacity );
  18626. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  18627. gl.uniform1f( uniforms.rotation, material.rotation );
  18628. gl.uniform2fv( uniforms.scale, scale );
  18629. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  18630. state.setDepthTest( material.depthTest );
  18631. state.setDepthWrite( material.depthWrite );
  18632. if ( material.map && material.map.image && material.map.image.width ) {
  18633. renderer.setTexture( material.map, 0 );
  18634. } else {
  18635. renderer.setTexture( texture, 0 );
  18636. }
  18637. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18638. }
  18639. // restore gl
  18640. state.enable( gl.CULL_FACE );
  18641. renderer.resetGLState();
  18642. };
  18643. function createProgram () {
  18644. var program = gl.createProgram();
  18645. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18646. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18647. gl.shaderSource( vertexShader, [
  18648. 'precision ' + renderer.getPrecision() + ' float;',
  18649. 'uniform mat4 modelViewMatrix;',
  18650. 'uniform mat4 projectionMatrix;',
  18651. 'uniform float rotation;',
  18652. 'uniform vec2 scale;',
  18653. 'uniform vec2 uvOffset;',
  18654. 'uniform vec2 uvScale;',
  18655. 'attribute vec2 position;',
  18656. 'attribute vec2 uv;',
  18657. 'varying vec2 vUV;',
  18658. 'void main() {',
  18659. 'vUV = uvOffset + uv * uvScale;',
  18660. 'vec2 alignedPosition = position * scale;',
  18661. 'vec2 rotatedPosition;',
  18662. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  18663. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  18664. 'vec4 finalPosition;',
  18665. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  18666. 'finalPosition.xy += rotatedPosition;',
  18667. 'finalPosition = projectionMatrix * finalPosition;',
  18668. 'gl_Position = finalPosition;',
  18669. '}'
  18670. ].join( '\n' ) );
  18671. gl.shaderSource( fragmentShader, [
  18672. 'precision ' + renderer.getPrecision() + ' float;',
  18673. 'uniform vec3 color;',
  18674. 'uniform sampler2D map;',
  18675. 'uniform float opacity;',
  18676. 'uniform int fogType;',
  18677. 'uniform vec3 fogColor;',
  18678. 'uniform float fogDensity;',
  18679. 'uniform float fogNear;',
  18680. 'uniform float fogFar;',
  18681. 'uniform float alphaTest;',
  18682. 'varying vec2 vUV;',
  18683. 'void main() {',
  18684. 'vec4 texture = texture2D( map, vUV );',
  18685. 'if ( texture.a < alphaTest ) discard;',
  18686. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  18687. 'if ( fogType > 0 ) {',
  18688. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  18689. 'float fogFactor = 0.0;',
  18690. 'if ( fogType == 1 ) {',
  18691. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  18692. '} else {',
  18693. 'const float LOG2 = 1.442695;',
  18694. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  18695. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  18696. '}',
  18697. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  18698. '}',
  18699. '}'
  18700. ].join( '\n' ) );
  18701. gl.compileShader( vertexShader );
  18702. gl.compileShader( fragmentShader );
  18703. gl.attachShader( program, vertexShader );
  18704. gl.attachShader( program, fragmentShader );
  18705. gl.linkProgram( program );
  18706. return program;
  18707. }
  18708. function painterSortStable ( a, b ) {
  18709. if ( a.z !== b.z ) {
  18710. return b.z - a.z;
  18711. } else {
  18712. return b.id - a.id;
  18713. }
  18714. }
  18715. };
  18716. // File:src/Three.Legacy.js
  18717. /**
  18718. * @author mrdoob / http://mrdoob.com/
  18719. */
  18720. Object.defineProperties( THREE.Box2.prototype, {
  18721. isIntersectionBox: {
  18722. value: function ( box ) {
  18723. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18724. return this.intersectsBox( box );
  18725. }
  18726. }
  18727. } );
  18728. Object.defineProperties( THREE.Box3.prototype, {
  18729. isIntersectionBox: {
  18730. value: function ( box ) {
  18731. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18732. return this.intersectsBox( box );
  18733. }
  18734. },
  18735. isIntersectionSphere: {
  18736. value: function ( sphere ) {
  18737. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18738. return this.intersectsSphere( sphere );
  18739. }
  18740. }
  18741. } );
  18742. Object.defineProperties( THREE.Matrix3.prototype, {
  18743. multiplyVector3: {
  18744. value: function ( vector ) {
  18745. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  18746. return vector.applyMatrix3( this );
  18747. }
  18748. },
  18749. multiplyVector3Array: {
  18750. value: function ( a ) {
  18751. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18752. return this.applyToVector3Array( a );
  18753. }
  18754. }
  18755. } );
  18756. Object.defineProperties( THREE.Matrix4.prototype, {
  18757. extractPosition: {
  18758. value: function ( m ) {
  18759. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  18760. return this.copyPosition( m );
  18761. }
  18762. },
  18763. setRotationFromQuaternion: {
  18764. value: function ( q ) {
  18765. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  18766. return this.makeRotationFromQuaternion( q );
  18767. }
  18768. },
  18769. multiplyVector3: {
  18770. value: function ( vector ) {
  18771. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  18772. return vector.applyProjection( this );
  18773. }
  18774. },
  18775. multiplyVector4: {
  18776. value: function ( vector ) {
  18777. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18778. return vector.applyMatrix4( this );
  18779. }
  18780. },
  18781. multiplyVector3Array: {
  18782. value: function ( a ) {
  18783. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18784. return this.applyToVector3Array( a );
  18785. }
  18786. },
  18787. rotateAxis: {
  18788. value: function ( v ) {
  18789. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  18790. v.transformDirection( this );
  18791. }
  18792. },
  18793. crossVector: {
  18794. value: function ( vector ) {
  18795. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18796. return vector.applyMatrix4( this );
  18797. }
  18798. },
  18799. translate: {
  18800. value: function ( v ) {
  18801. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  18802. }
  18803. },
  18804. rotateX: {
  18805. value: function ( angle ) {
  18806. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  18807. }
  18808. },
  18809. rotateY: {
  18810. value: function ( angle ) {
  18811. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  18812. }
  18813. },
  18814. rotateZ: {
  18815. value: function ( angle ) {
  18816. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  18817. }
  18818. },
  18819. rotateByAxis: {
  18820. value: function ( axis, angle ) {
  18821. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  18822. }
  18823. }
  18824. } );
  18825. Object.defineProperties( THREE.Plane.prototype, {
  18826. isIntersectionLine: {
  18827. value: function ( line ) {
  18828. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  18829. return this.intersectsLine( line );
  18830. }
  18831. }
  18832. } );
  18833. Object.defineProperties( THREE.Quaternion.prototype, {
  18834. multiplyVector3: {
  18835. value: function ( vector ) {
  18836. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  18837. return vector.applyQuaternion( this );
  18838. }
  18839. }
  18840. } );
  18841. Object.defineProperties( THREE.Ray.prototype, {
  18842. isIntersectionBox: {
  18843. value: function ( box ) {
  18844. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18845. return this.intersectsBox( box );
  18846. }
  18847. },
  18848. isIntersectionPlane: {
  18849. value: function ( plane ) {
  18850. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  18851. return this.intersectsPlane( plane );
  18852. }
  18853. },
  18854. isIntersectionSphere: {
  18855. value: function ( sphere ) {
  18856. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18857. return this.intersectsSphere( sphere );
  18858. }
  18859. }
  18860. } );
  18861. Object.defineProperties( THREE.Vector3.prototype, {
  18862. setEulerFromRotationMatrix: {
  18863. value: function () {
  18864. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  18865. }
  18866. },
  18867. setEulerFromQuaternion: {
  18868. value: function () {
  18869. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  18870. }
  18871. },
  18872. getPositionFromMatrix: {
  18873. value: function ( m ) {
  18874. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  18875. return this.setFromMatrixPosition( m );
  18876. }
  18877. },
  18878. getScaleFromMatrix: {
  18879. value: function ( m ) {
  18880. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  18881. return this.setFromMatrixScale( m );
  18882. }
  18883. },
  18884. getColumnFromMatrix: {
  18885. value: function ( index, matrix ) {
  18886. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  18887. return this.setFromMatrixColumn( index, matrix );
  18888. }
  18889. }
  18890. } );
  18891. //
  18892. Object.defineProperties( THREE.Object3D.prototype, {
  18893. eulerOrder: {
  18894. get: function () {
  18895. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  18896. return this.rotation.order;
  18897. },
  18898. set: function ( value ) {
  18899. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  18900. this.rotation.order = value;
  18901. }
  18902. },
  18903. getChildByName: {
  18904. value: function ( name ) {
  18905. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  18906. return this.getObjectByName( name );
  18907. }
  18908. },
  18909. renderDepth: {
  18910. set: function ( value ) {
  18911. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  18912. }
  18913. },
  18914. translate: {
  18915. value: function ( distance, axis ) {
  18916. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  18917. return this.translateOnAxis( axis, distance );
  18918. }
  18919. },
  18920. useQuaternion: {
  18921. get: function () {
  18922. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  18923. },
  18924. set: function ( value ) {
  18925. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  18926. }
  18927. }
  18928. } );
  18929. //
  18930. Object.defineProperties( THREE, {
  18931. PointCloud: {
  18932. value: function ( geometry, material ) {
  18933. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  18934. return new THREE.Points( geometry, material );
  18935. }
  18936. },
  18937. ParticleSystem: {
  18938. value: function ( geometry, material ) {
  18939. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  18940. return new THREE.Points( geometry, material );
  18941. }
  18942. }
  18943. } );
  18944. //
  18945. Object.defineProperties( THREE.Light.prototype, {
  18946. onlyShadow: {
  18947. set: function ( value ) {
  18948. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  18949. }
  18950. },
  18951. shadowCameraFov: {
  18952. set: function ( value ) {
  18953. this.shadow.camera.fov = value;
  18954. }
  18955. },
  18956. shadowCameraLeft: {
  18957. set: function ( value ) {
  18958. this.shadow.camera.left = value;
  18959. }
  18960. },
  18961. shadowCameraRight: {
  18962. set: function ( value ) {
  18963. this.shadow.camera.right = value;
  18964. }
  18965. },
  18966. shadowCameraTop: {
  18967. set: function ( value ) {
  18968. this.shadow.camera.top = value;
  18969. }
  18970. },
  18971. shadowCameraBottom: {
  18972. set: function ( value ) {
  18973. this.shadow.camera.bottom = value;
  18974. }
  18975. },
  18976. shadowCameraNear: {
  18977. set: function ( value ) {
  18978. this.shadow.camera.near = value;
  18979. }
  18980. },
  18981. shadowCameraFar: {
  18982. set: function ( value ) {
  18983. this.shadow.camera.far = value;
  18984. }
  18985. },
  18986. shadowCameraVisible: {
  18987. set: function ( value ) {
  18988. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  18989. }
  18990. },
  18991. shadowBias: {
  18992. set: function ( value ) {
  18993. this.shadow.bias = value;
  18994. }
  18995. },
  18996. shadowDarkness: {
  18997. set: function ( value ) {
  18998. this.shadow.darkness = value;
  18999. }
  19000. },
  19001. shadowMapWidth: {
  19002. set: function ( value ) {
  19003. this.shadow.mapSize.width = value;
  19004. }
  19005. },
  19006. shadowMapHeight: {
  19007. set: function ( value ) {
  19008. this.shadow.mapSize.height = value;
  19009. }
  19010. }
  19011. } );
  19012. //
  19013. Object.defineProperties( THREE.BufferAttribute.prototype, {
  19014. length: {
  19015. get: function () {
  19016. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  19017. return this.array.length;
  19018. }
  19019. }
  19020. } );
  19021. //
  19022. Object.defineProperties( THREE.Material.prototype, {
  19023. wrapAround: {
  19024. get: function () {
  19025. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19026. },
  19027. set: function ( value ) {
  19028. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19029. }
  19030. },
  19031. wrapRGB: {
  19032. get: function () {
  19033. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  19034. return new THREE.Color();
  19035. }
  19036. }
  19037. } );
  19038. Object.defineProperties( THREE, {
  19039. PointCloudMaterial: {
  19040. value: function ( parameters ) {
  19041. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  19042. return new THREE.PointsMaterial( parameters );
  19043. }
  19044. },
  19045. ParticleBasicMaterial: {
  19046. value: function ( parameters ) {
  19047. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  19048. return new THREE.PointsMaterial( parameters );
  19049. }
  19050. },
  19051. ParticleSystemMaterial:{
  19052. value: function ( parameters ) {
  19053. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  19054. return new THREE.PointsMaterial( parameters );
  19055. }
  19056. }
  19057. } );
  19058. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  19059. metal: {
  19060. get: function () {
  19061. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  19062. return false;
  19063. },
  19064. set: function ( value ) {
  19065. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  19066. }
  19067. }
  19068. } );
  19069. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  19070. derivatives: {
  19071. get: function () {
  19072. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19073. return this.extensions.derivatives;
  19074. },
  19075. set: function ( value ) {
  19076. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19077. this.extensions.derivatives = value;
  19078. }
  19079. }
  19080. } );
  19081. //
  19082. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  19083. supportsFloatTextures: {
  19084. value: function () {
  19085. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  19086. return this.extensions.get( 'OES_texture_float' );
  19087. }
  19088. },
  19089. supportsHalfFloatTextures: {
  19090. value: function () {
  19091. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  19092. return this.extensions.get( 'OES_texture_half_float' );
  19093. }
  19094. },
  19095. supportsStandardDerivatives: {
  19096. value: function () {
  19097. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  19098. return this.extensions.get( 'OES_standard_derivatives' );
  19099. }
  19100. },
  19101. supportsCompressedTextureS3TC: {
  19102. value: function () {
  19103. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19104. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19105. }
  19106. },
  19107. supportsCompressedTexturePVRTC: {
  19108. value: function () {
  19109. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19110. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19111. }
  19112. },
  19113. supportsBlendMinMax: {
  19114. value: function () {
  19115. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19116. return this.extensions.get( 'EXT_blend_minmax' );
  19117. }
  19118. },
  19119. supportsVertexTextures: {
  19120. value: function () {
  19121. return this.capabilities.vertexTextures;
  19122. }
  19123. },
  19124. supportsInstancedArrays: {
  19125. value: function () {
  19126. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19127. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19128. }
  19129. },
  19130. initMaterial: {
  19131. value: function () {
  19132. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19133. }
  19134. },
  19135. addPrePlugin: {
  19136. value: function () {
  19137. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19138. }
  19139. },
  19140. addPostPlugin: {
  19141. value: function () {
  19142. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19143. }
  19144. },
  19145. updateShadowMap: {
  19146. value: function () {
  19147. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19148. }
  19149. },
  19150. shadowMapEnabled: {
  19151. get: function () {
  19152. return this.shadowMap.enabled;
  19153. },
  19154. set: function ( value ) {
  19155. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19156. this.shadowMap.enabled = value;
  19157. }
  19158. },
  19159. shadowMapType: {
  19160. get: function () {
  19161. return this.shadowMap.type;
  19162. },
  19163. set: function ( value ) {
  19164. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19165. this.shadowMap.type = value;
  19166. }
  19167. },
  19168. shadowMapCullFace: {
  19169. get: function () {
  19170. return this.shadowMap.cullFace;
  19171. },
  19172. set: function ( value ) {
  19173. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19174. this.shadowMap.cullFace = value;
  19175. }
  19176. },
  19177. shadowMapDebug: {
  19178. get: function () {
  19179. return this.shadowMap.debug;
  19180. },
  19181. set: function ( value ) {
  19182. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  19183. this.shadowMap.debug = value;
  19184. }
  19185. }
  19186. } );
  19187. //
  19188. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19189. wrapS: {
  19190. get: function () {
  19191. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19192. return this.texture.wrapS;
  19193. },
  19194. set: function ( value ) {
  19195. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19196. this.texture.wrapS = value;
  19197. }
  19198. },
  19199. wrapT: {
  19200. get: function () {
  19201. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19202. return this.texture.wrapT;
  19203. },
  19204. set: function ( value ) {
  19205. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19206. this.texture.wrapT = value;
  19207. }
  19208. },
  19209. magFilter: {
  19210. get: function () {
  19211. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19212. return this.texture.magFilter;
  19213. },
  19214. set: function ( value ) {
  19215. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19216. this.texture.magFilter = value;
  19217. }
  19218. },
  19219. minFilter: {
  19220. get: function () {
  19221. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19222. return this.texture.minFilter;
  19223. },
  19224. set: function ( value ) {
  19225. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19226. this.texture.minFilter = value;
  19227. }
  19228. },
  19229. anisotropy: {
  19230. get: function () {
  19231. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19232. return this.texture.anisotropy;
  19233. },
  19234. set: function ( value ) {
  19235. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19236. this.texture.anisotropy = value;
  19237. }
  19238. },
  19239. offset: {
  19240. get: function () {
  19241. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19242. return this.texture.offset;
  19243. },
  19244. set: function ( value ) {
  19245. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19246. this.texture.offset = value;
  19247. }
  19248. },
  19249. repeat: {
  19250. get: function () {
  19251. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19252. return this.texture.repeat;
  19253. },
  19254. set: function ( value ) {
  19255. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19256. this.texture.repeat = value;
  19257. }
  19258. },
  19259. format: {
  19260. get: function () {
  19261. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19262. return this.texture.format;
  19263. },
  19264. set: function ( value ) {
  19265. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19266. this.texture.format = value;
  19267. }
  19268. },
  19269. type: {
  19270. get: function () {
  19271. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19272. return this.texture.type;
  19273. },
  19274. set: function ( value ) {
  19275. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19276. this.texture.type = value;
  19277. }
  19278. },
  19279. generateMipmaps: {
  19280. get: function () {
  19281. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19282. return this.texture.generateMipmaps;
  19283. },
  19284. set: function ( value ) {
  19285. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19286. this.texture.generateMipmaps = value;
  19287. }
  19288. }
  19289. } );
  19290. //
  19291. THREE.GeometryUtils = {
  19292. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19293. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19294. var matrix;
  19295. if ( geometry2 instanceof THREE.Mesh ) {
  19296. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19297. matrix = geometry2.matrix;
  19298. geometry2 = geometry2.geometry;
  19299. }
  19300. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19301. },
  19302. center: function ( geometry ) {
  19303. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19304. return geometry.center();
  19305. }
  19306. };
  19307. THREE.ImageUtils = {
  19308. crossOrigin: undefined,
  19309. loadTexture: function ( url, mapping, onLoad, onError ) {
  19310. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19311. var loader = new THREE.TextureLoader();
  19312. loader.setCrossOrigin( this.crossOrigin );
  19313. var texture = loader.load( url, onLoad, undefined, onError );
  19314. if ( mapping ) texture.mapping = mapping;
  19315. return texture;
  19316. },
  19317. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19318. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19319. var loader = new THREE.CubeTextureLoader();
  19320. loader.setCrossOrigin( this.crossOrigin );
  19321. var texture = loader.load( urls, onLoad, undefined, onError );
  19322. if ( mapping ) texture.mapping = mapping;
  19323. return texture;
  19324. },
  19325. loadCompressedTexture: function () {
  19326. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  19327. },
  19328. loadCompressedTextureCube: function () {
  19329. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  19330. }
  19331. };
  19332. //
  19333. THREE.Projector = function () {
  19334. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  19335. this.projectVector = function ( vector, camera ) {
  19336. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  19337. vector.project( camera );
  19338. };
  19339. this.unprojectVector = function ( vector, camera ) {
  19340. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  19341. vector.unproject( camera );
  19342. };
  19343. this.pickingRay = function ( vector, camera ) {
  19344. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  19345. };
  19346. };
  19347. //
  19348. THREE.CanvasRenderer = function () {
  19349. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  19350. this.domElement = document.createElement( 'canvas' );
  19351. this.clear = function () {};
  19352. this.render = function () {};
  19353. this.setClearColor = function () {};
  19354. this.setSize = function () {};
  19355. };
  19356. //
  19357. THREE.TextGeometry = function () {
  19358. console.error( 'THREE.TextGeometry has been moved to /examples/js/geometries/TextGeometry.js' );
  19359. console.error( 'THREE.FontUtils has been moved to /examples/js/utils/FontUtils.js' );
  19360. };
  19361. // File:src/extras/CurveUtils.js
  19362. /**
  19363. * @author zz85 / http://www.lab4games.net/zz85/blog
  19364. */
  19365. THREE.CurveUtils = {
  19366. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  19367. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  19368. },
  19369. // Puay Bing, thanks for helping with this derivative!
  19370. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  19371. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  19372. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  19373. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  19374. 3 * t * t * p3;
  19375. },
  19376. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  19377. // To check if my formulas are correct
  19378. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  19379. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  19380. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  19381. var h11 = 3 * t * t - 2 * t; // t3 − t2
  19382. return h00 + h10 + h01 + h11;
  19383. },
  19384. // Catmull-Rom
  19385. interpolate: function( p0, p1, p2, p3, t ) {
  19386. var v0 = ( p2 - p0 ) * 0.5;
  19387. var v1 = ( p3 - p1 ) * 0.5;
  19388. var t2 = t * t;
  19389. var t3 = t * t2;
  19390. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19391. }
  19392. };
  19393. // File:src/extras/SceneUtils.js
  19394. /**
  19395. * @author alteredq / http://alteredqualia.com/
  19396. */
  19397. THREE.SceneUtils = {
  19398. createMultiMaterialObject: function ( geometry, materials ) {
  19399. var group = new THREE.Group();
  19400. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  19401. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  19402. }
  19403. return group;
  19404. },
  19405. detach: function ( child, parent, scene ) {
  19406. child.applyMatrix( parent.matrixWorld );
  19407. parent.remove( child );
  19408. scene.add( child );
  19409. },
  19410. attach: function ( child, scene, parent ) {
  19411. var matrixWorldInverse = new THREE.Matrix4();
  19412. matrixWorldInverse.getInverse( parent.matrixWorld );
  19413. child.applyMatrix( matrixWorldInverse );
  19414. scene.remove( child );
  19415. parent.add( child );
  19416. }
  19417. };
  19418. // File:src/extras/ShapeUtils.js
  19419. /**
  19420. * @author zz85 / http://www.lab4games.net/zz85/blog
  19421. */
  19422. THREE.ShapeUtils = {
  19423. // calculate area of the contour polygon
  19424. area: function ( contour ) {
  19425. var n = contour.length;
  19426. var a = 0.0;
  19427. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19428. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19429. }
  19430. return a * 0.5;
  19431. },
  19432. triangulate: ( function () {
  19433. /**
  19434. * This code is a quick port of code written in C++ which was submitted to
  19435. * flipcode.com by John W. Ratcliff // July 22, 2000
  19436. * See original code and more information here:
  19437. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19438. *
  19439. * ported to actionscript by Zevan Rosser
  19440. * www.actionsnippet.com
  19441. *
  19442. * ported to javascript by Joshua Koo
  19443. * http://www.lab4games.net/zz85/blog
  19444. *
  19445. */
  19446. function snip( contour, u, v, w, n, verts ) {
  19447. var p;
  19448. var ax, ay, bx, by;
  19449. var cx, cy, px, py;
  19450. ax = contour[ verts[ u ] ].x;
  19451. ay = contour[ verts[ u ] ].y;
  19452. bx = contour[ verts[ v ] ].x;
  19453. by = contour[ verts[ v ] ].y;
  19454. cx = contour[ verts[ w ] ].x;
  19455. cy = contour[ verts[ w ] ].y;
  19456. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  19457. var aX, aY, bX, bY, cX, cY;
  19458. var apx, apy, bpx, bpy, cpx, cpy;
  19459. var cCROSSap, bCROSScp, aCROSSbp;
  19460. aX = cx - bx; aY = cy - by;
  19461. bX = ax - cx; bY = ay - cy;
  19462. cX = bx - ax; cY = by - ay;
  19463. for ( p = 0; p < n; p ++ ) {
  19464. px = contour[ verts[ p ] ].x;
  19465. py = contour[ verts[ p ] ].y;
  19466. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19467. ( ( px === bx ) && ( py === by ) ) ||
  19468. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19469. apx = px - ax; apy = py - ay;
  19470. bpx = px - bx; bpy = py - by;
  19471. cpx = px - cx; cpy = py - cy;
  19472. // see if p is inside triangle abc
  19473. aCROSSbp = aX * bpy - aY * bpx;
  19474. cCROSSap = cX * apy - cY * apx;
  19475. bCROSScp = bX * cpy - bY * cpx;
  19476. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19477. }
  19478. return true;
  19479. }
  19480. // takes in an contour array and returns
  19481. return function ( contour, indices ) {
  19482. var n = contour.length;
  19483. if ( n < 3 ) return null;
  19484. var result = [],
  19485. verts = [],
  19486. vertIndices = [];
  19487. /* we want a counter-clockwise polygon in verts */
  19488. var u, v, w;
  19489. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  19490. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19491. } else {
  19492. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19493. }
  19494. var nv = n;
  19495. /* remove nv - 2 vertices, creating 1 triangle every time */
  19496. var count = 2 * nv; /* error detection */
  19497. for ( v = nv - 1; nv > 2; ) {
  19498. /* if we loop, it is probably a non-simple polygon */
  19499. if ( ( count -- ) <= 0 ) {
  19500. //** Triangulate: ERROR - probable bad polygon!
  19501. //throw ( "Warning, unable to triangulate polygon!" );
  19502. //return null;
  19503. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19504. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19505. if ( indices ) return vertIndices;
  19506. return result;
  19507. }
  19508. /* three consecutive vertices in current polygon, <u,v,w> */
  19509. u = v; if ( nv <= u ) u = 0; /* previous */
  19510. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19511. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19512. if ( snip( contour, u, v, w, nv, verts ) ) {
  19513. var a, b, c, s, t;
  19514. /* true names of the vertices */
  19515. a = verts[ u ];
  19516. b = verts[ v ];
  19517. c = verts[ w ];
  19518. /* output Triangle */
  19519. result.push( [ contour[ a ],
  19520. contour[ b ],
  19521. contour[ c ] ] );
  19522. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19523. /* remove v from the remaining polygon */
  19524. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19525. verts[ s ] = verts[ t ];
  19526. }
  19527. nv --;
  19528. /* reset error detection counter */
  19529. count = 2 * nv;
  19530. }
  19531. }
  19532. if ( indices ) return vertIndices;
  19533. return result;
  19534. }
  19535. } )(),
  19536. triangulateShape: function ( contour, holes ) {
  19537. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19538. // inOtherPt needs to be collinear to the inSegment
  19539. if ( inSegPt1.x !== inSegPt2.x ) {
  19540. if ( inSegPt1.x < inSegPt2.x ) {
  19541. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19542. } else {
  19543. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19544. }
  19545. } else {
  19546. if ( inSegPt1.y < inSegPt2.y ) {
  19547. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19548. } else {
  19549. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19550. }
  19551. }
  19552. }
  19553. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19554. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19555. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19556. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19557. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19558. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19559. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19560. if ( Math.abs( limit ) > Number.EPSILON ) {
  19561. // not parallel
  19562. var perpSeg2;
  19563. if ( limit > 0 ) {
  19564. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19565. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19566. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19567. } else {
  19568. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19569. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19570. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19571. }
  19572. // i.e. to reduce rounding errors
  19573. // intersection at endpoint of segment#1?
  19574. if ( perpSeg2 === 0 ) {
  19575. if ( ( inExcludeAdjacentSegs ) &&
  19576. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19577. return [ inSeg1Pt1 ];
  19578. }
  19579. if ( perpSeg2 === limit ) {
  19580. if ( ( inExcludeAdjacentSegs ) &&
  19581. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19582. return [ inSeg1Pt2 ];
  19583. }
  19584. // intersection at endpoint of segment#2?
  19585. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19586. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19587. // return real intersection point
  19588. var factorSeg1 = perpSeg2 / limit;
  19589. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19590. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19591. } else {
  19592. // parallel or collinear
  19593. if ( ( perpSeg1 !== 0 ) ||
  19594. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19595. // they are collinear or degenerate
  19596. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19597. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19598. // both segments are points
  19599. if ( seg1Pt && seg2Pt ) {
  19600. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19601. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19602. return [ inSeg1Pt1 ]; // they are the same point
  19603. }
  19604. // segment#1 is a single point
  19605. if ( seg1Pt ) {
  19606. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19607. return [ inSeg1Pt1 ];
  19608. }
  19609. // segment#2 is a single point
  19610. if ( seg2Pt ) {
  19611. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19612. return [ inSeg2Pt1 ];
  19613. }
  19614. // they are collinear segments, which might overlap
  19615. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19616. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19617. if ( seg1dx !== 0 ) {
  19618. // the segments are NOT on a vertical line
  19619. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19620. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19621. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19622. } else {
  19623. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19624. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19625. }
  19626. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19627. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19628. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19629. } else {
  19630. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19631. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19632. }
  19633. } else {
  19634. // the segments are on a vertical line
  19635. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19636. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19637. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19638. } else {
  19639. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19640. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19641. }
  19642. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19643. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19644. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19645. } else {
  19646. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19647. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19648. }
  19649. }
  19650. if ( seg1minVal <= seg2minVal ) {
  19651. if ( seg1maxVal < seg2minVal ) return [];
  19652. if ( seg1maxVal === seg2minVal ) {
  19653. if ( inExcludeAdjacentSegs ) return [];
  19654. return [ seg2min ];
  19655. }
  19656. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19657. return [ seg2min, seg2max ];
  19658. } else {
  19659. if ( seg1minVal > seg2maxVal ) return [];
  19660. if ( seg1minVal === seg2maxVal ) {
  19661. if ( inExcludeAdjacentSegs ) return [];
  19662. return [ seg1min ];
  19663. }
  19664. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19665. return [ seg1min, seg2max ];
  19666. }
  19667. }
  19668. }
  19669. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19670. // The order of legs is important
  19671. // translation of all points, so that Vertex is at (0,0)
  19672. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19673. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19674. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19675. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19676. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19677. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19678. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19679. // angle != 180 deg.
  19680. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19681. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19682. if ( from2toAngle > 0 ) {
  19683. // main angle < 180 deg.
  19684. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19685. } else {
  19686. // main angle > 180 deg.
  19687. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19688. }
  19689. } else {
  19690. // angle == 180 deg.
  19691. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19692. return ( from2otherAngle > 0 );
  19693. }
  19694. }
  19695. function removeHoles( contour, holes ) {
  19696. var shape = contour.concat(); // work on this shape
  19697. var hole;
  19698. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19699. // Check if hole point lies within angle around shape point
  19700. var lastShapeIdx = shape.length - 1;
  19701. var prevShapeIdx = inShapeIdx - 1;
  19702. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19703. var nextShapeIdx = inShapeIdx + 1;
  19704. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19705. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19706. if ( ! insideAngle ) {
  19707. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19708. return false;
  19709. }
  19710. // Check if shape point lies within angle around hole point
  19711. var lastHoleIdx = hole.length - 1;
  19712. var prevHoleIdx = inHoleIdx - 1;
  19713. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19714. var nextHoleIdx = inHoleIdx + 1;
  19715. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19716. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19717. if ( ! insideAngle ) {
  19718. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19719. return false;
  19720. }
  19721. return true;
  19722. }
  19723. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19724. // checks for intersections with shape edges
  19725. var sIdx, nextIdx, intersection;
  19726. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19727. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19728. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19729. if ( intersection.length > 0 ) return true;
  19730. }
  19731. return false;
  19732. }
  19733. var indepHoles = [];
  19734. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19735. // checks for intersections with hole edges
  19736. var ihIdx, chkHole,
  19737. hIdx, nextIdx, intersection;
  19738. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19739. chkHole = holes[ indepHoles[ ihIdx ]];
  19740. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19741. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19742. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19743. if ( intersection.length > 0 ) return true;
  19744. }
  19745. }
  19746. return false;
  19747. }
  19748. var holeIndex, shapeIndex,
  19749. shapePt, holePt,
  19750. holeIdx, cutKey, failedCuts = [],
  19751. tmpShape1, tmpShape2,
  19752. tmpHole1, tmpHole2;
  19753. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19754. indepHoles.push( h );
  19755. }
  19756. var minShapeIndex = 0;
  19757. var counter = indepHoles.length * 2;
  19758. while ( indepHoles.length > 0 ) {
  19759. counter --;
  19760. if ( counter < 0 ) {
  19761. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19762. break;
  19763. }
  19764. // search for shape-vertex and hole-vertex,
  19765. // which can be connected without intersections
  19766. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19767. shapePt = shape[ shapeIndex ];
  19768. holeIndex = - 1;
  19769. // search for hole which can be reached without intersections
  19770. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19771. holeIdx = indepHoles[ h ];
  19772. // prevent multiple checks
  19773. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19774. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19775. hole = holes[ holeIdx ];
  19776. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19777. holePt = hole[ h2 ];
  19778. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19779. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19780. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19781. holeIndex = h2;
  19782. indepHoles.splice( h, 1 );
  19783. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19784. tmpShape2 = shape.slice( shapeIndex );
  19785. tmpHole1 = hole.slice( holeIndex );
  19786. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19787. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19788. minShapeIndex = shapeIndex;
  19789. // Debug only, to show the selected cuts
  19790. // glob_CutLines.push( [ shapePt, holePt ] );
  19791. break;
  19792. }
  19793. if ( holeIndex >= 0 ) break; // hole-vertex found
  19794. failedCuts[ cutKey ] = true; // remember failure
  19795. }
  19796. if ( holeIndex >= 0 ) break; // hole-vertex found
  19797. }
  19798. }
  19799. return shape; /* shape with no holes */
  19800. }
  19801. var i, il, f, face,
  19802. key, index,
  19803. allPointsMap = {};
  19804. // 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.
  19805. var allpoints = contour.concat();
  19806. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19807. Array.prototype.push.apply( allpoints, holes[ h ] );
  19808. }
  19809. //console.log( "allpoints",allpoints, allpoints.length );
  19810. // prepare all points map
  19811. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19812. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19813. if ( allPointsMap[ key ] !== undefined ) {
  19814. console.warn( "THREE.Shape: Duplicate point", key );
  19815. }
  19816. allPointsMap[ key ] = i;
  19817. }
  19818. // remove holes by cutting paths to holes and adding them to the shape
  19819. var shapeWithoutHoles = removeHoles( contour, holes );
  19820. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19821. //console.log( "triangles",triangles, triangles.length );
  19822. // check all face vertices against all points map
  19823. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19824. face = triangles[ i ];
  19825. for ( f = 0; f < 3; f ++ ) {
  19826. key = face[ f ].x + ":" + face[ f ].y;
  19827. index = allPointsMap[ key ];
  19828. if ( index !== undefined ) {
  19829. face[ f ] = index;
  19830. }
  19831. }
  19832. }
  19833. return triangles.concat();
  19834. },
  19835. isClockWise: function ( pts ) {
  19836. return THREE.ShapeUtils.area( pts ) < 0;
  19837. },
  19838. // Bezier Curves formulas obtained from
  19839. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19840. // Quad Bezier Functions
  19841. b2: ( function () {
  19842. function b2p0( t, p ) {
  19843. var k = 1 - t;
  19844. return k * k * p;
  19845. }
  19846. function b2p1( t, p ) {
  19847. return 2 * ( 1 - t ) * t * p;
  19848. }
  19849. function b2p2( t, p ) {
  19850. return t * t * p;
  19851. }
  19852. return function ( t, p0, p1, p2 ) {
  19853. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  19854. };
  19855. } )(),
  19856. // Cubic Bezier Functions
  19857. b3: ( function () {
  19858. function b3p0( t, p ) {
  19859. var k = 1 - t;
  19860. return k * k * k * p;
  19861. }
  19862. function b3p1( t, p ) {
  19863. var k = 1 - t;
  19864. return 3 * k * k * t * p;
  19865. }
  19866. function b3p2( t, p ) {
  19867. var k = 1 - t;
  19868. return 3 * k * t * t * p;
  19869. }
  19870. function b3p3( t, p ) {
  19871. return t * t * t * p;
  19872. }
  19873. return function ( t, p0, p1, p2, p3 ) {
  19874. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  19875. };
  19876. } )()
  19877. };
  19878. // File:src/extras/core/Curve.js
  19879. /**
  19880. * @author zz85 / http://www.lab4games.net/zz85/blog
  19881. * Extensible curve object
  19882. *
  19883. * Some common of Curve methods
  19884. * .getPoint(t), getTangent(t)
  19885. * .getPointAt(u), getTagentAt(u)
  19886. * .getPoints(), .getSpacedPoints()
  19887. * .getLength()
  19888. * .updateArcLengths()
  19889. *
  19890. * This following classes subclasses THREE.Curve:
  19891. *
  19892. * -- 2d classes --
  19893. * THREE.LineCurve
  19894. * THREE.QuadraticBezierCurve
  19895. * THREE.CubicBezierCurve
  19896. * THREE.SplineCurve
  19897. * THREE.ArcCurve
  19898. * THREE.EllipseCurve
  19899. *
  19900. * -- 3d classes --
  19901. * THREE.LineCurve3
  19902. * THREE.QuadraticBezierCurve3
  19903. * THREE.CubicBezierCurve3
  19904. * THREE.SplineCurve3
  19905. * THREE.ClosedSplineCurve3
  19906. *
  19907. * A series of curves can be represented as a THREE.CurvePath
  19908. *
  19909. **/
  19910. /**************************************************************
  19911. * Abstract Curve base class
  19912. **************************************************************/
  19913. THREE.Curve = function () {
  19914. };
  19915. THREE.Curve.prototype = {
  19916. constructor: THREE.Curve,
  19917. // Virtual base class method to overwrite and implement in subclasses
  19918. // - t [0 .. 1]
  19919. getPoint: function ( t ) {
  19920. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  19921. return null;
  19922. },
  19923. // Get point at relative position in curve according to arc length
  19924. // - u [0 .. 1]
  19925. getPointAt: function ( u ) {
  19926. var t = this.getUtoTmapping( u );
  19927. return this.getPoint( t );
  19928. },
  19929. // Get sequence of points using getPoint( t )
  19930. getPoints: function ( divisions ) {
  19931. if ( ! divisions ) divisions = 5;
  19932. var d, pts = [];
  19933. for ( d = 0; d <= divisions; d ++ ) {
  19934. pts.push( this.getPoint( d / divisions ) );
  19935. }
  19936. return pts;
  19937. },
  19938. // Get sequence of points using getPointAt( u )
  19939. getSpacedPoints: function ( divisions ) {
  19940. if ( ! divisions ) divisions = 5;
  19941. var d, pts = [];
  19942. for ( d = 0; d <= divisions; d ++ ) {
  19943. pts.push( this.getPointAt( d / divisions ) );
  19944. }
  19945. return pts;
  19946. },
  19947. // Get total curve arc length
  19948. getLength: function () {
  19949. var lengths = this.getLengths();
  19950. return lengths[ lengths.length - 1 ];
  19951. },
  19952. // Get list of cumulative segment lengths
  19953. getLengths: function ( divisions ) {
  19954. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  19955. if ( this.cacheArcLengths
  19956. && ( this.cacheArcLengths.length === divisions + 1 )
  19957. && ! this.needsUpdate ) {
  19958. //console.log( "cached", this.cacheArcLengths );
  19959. return this.cacheArcLengths;
  19960. }
  19961. this.needsUpdate = false;
  19962. var cache = [];
  19963. var current, last = this.getPoint( 0 );
  19964. var p, sum = 0;
  19965. cache.push( 0 );
  19966. for ( p = 1; p <= divisions; p ++ ) {
  19967. current = this.getPoint ( p / divisions );
  19968. sum += current.distanceTo( last );
  19969. cache.push( sum );
  19970. last = current;
  19971. }
  19972. this.cacheArcLengths = cache;
  19973. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  19974. },
  19975. updateArcLengths: function() {
  19976. this.needsUpdate = true;
  19977. this.getLengths();
  19978. },
  19979. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19980. getUtoTmapping: function ( u, distance ) {
  19981. var arcLengths = this.getLengths();
  19982. var i = 0, il = arcLengths.length;
  19983. var targetArcLength; // The targeted u distance value to get
  19984. if ( distance ) {
  19985. targetArcLength = distance;
  19986. } else {
  19987. targetArcLength = u * arcLengths[ il - 1 ];
  19988. }
  19989. //var time = Date.now();
  19990. // binary search for the index with largest value smaller than target u distance
  19991. var low = 0, high = il - 1, comparison;
  19992. while ( low <= high ) {
  19993. 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
  19994. comparison = arcLengths[ i ] - targetArcLength;
  19995. if ( comparison < 0 ) {
  19996. low = i + 1;
  19997. } else if ( comparison > 0 ) {
  19998. high = i - 1;
  19999. } else {
  20000. high = i;
  20001. break;
  20002. // DONE
  20003. }
  20004. }
  20005. i = high;
  20006. //console.log('b' , i, low, high, Date.now()- time);
  20007. if ( arcLengths[ i ] === targetArcLength ) {
  20008. var t = i / ( il - 1 );
  20009. return t;
  20010. }
  20011. // we could get finer grain at lengths, or use simple interpolation between two points
  20012. var lengthBefore = arcLengths[ i ];
  20013. var lengthAfter = arcLengths[ i + 1 ];
  20014. var segmentLength = lengthAfter - lengthBefore;
  20015. // determine where we are between the 'before' and 'after' points
  20016. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20017. // add that fractional amount to t
  20018. var t = ( i + segmentFraction ) / ( il - 1 );
  20019. return t;
  20020. },
  20021. // Returns a unit vector tangent at t
  20022. // In case any sub curve does not implement its tangent derivation,
  20023. // 2 points a small delta apart will be used to find its gradient
  20024. // which seems to give a reasonable approximation
  20025. getTangent: function( t ) {
  20026. var delta = 0.0001;
  20027. var t1 = t - delta;
  20028. var t2 = t + delta;
  20029. // Capping in case of danger
  20030. if ( t1 < 0 ) t1 = 0;
  20031. if ( t2 > 1 ) t2 = 1;
  20032. var pt1 = this.getPoint( t1 );
  20033. var pt2 = this.getPoint( t2 );
  20034. var vec = pt2.clone().sub( pt1 );
  20035. return vec.normalize();
  20036. },
  20037. getTangentAt: function ( u ) {
  20038. var t = this.getUtoTmapping( u );
  20039. return this.getTangent( t );
  20040. }
  20041. }
  20042. THREE.Curve.Utils = THREE.CurveUtils; // backwards compatibility
  20043. // TODO: Transformation for Curves?
  20044. /**************************************************************
  20045. * 3D Curves
  20046. **************************************************************/
  20047. // A Factory method for creating new curve subclasses
  20048. THREE.Curve.create = function ( constructor, getPointFunc ) {
  20049. constructor.prototype = Object.create( THREE.Curve.prototype );
  20050. constructor.prototype.constructor = constructor;
  20051. constructor.prototype.getPoint = getPointFunc;
  20052. return constructor;
  20053. };
  20054. // File:src/extras/core/CurvePath.js
  20055. /**
  20056. * @author zz85 / http://www.lab4games.net/zz85/blog
  20057. *
  20058. **/
  20059. /**************************************************************
  20060. * Curved Path - a curve path is simply a array of connected
  20061. * curves, but retains the api of a curve
  20062. **************************************************************/
  20063. THREE.CurvePath = function () {
  20064. this.curves = [];
  20065. this.autoClose = false; // Automatically closes the path
  20066. };
  20067. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  20068. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  20069. THREE.CurvePath.prototype.add = function ( curve ) {
  20070. this.curves.push( curve );
  20071. };
  20072. /*
  20073. THREE.CurvePath.prototype.checkConnection = function() {
  20074. // TODO
  20075. // If the ending of curve is not connected to the starting
  20076. // or the next curve, then, this is not a real path
  20077. };
  20078. */
  20079. THREE.CurvePath.prototype.closePath = function() {
  20080. // TODO Test
  20081. // and verify for vector3 (needs to implement equals)
  20082. // Add a line curve if start and end of lines are not connected
  20083. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20084. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20085. if ( ! startPoint.equals( endPoint ) ) {
  20086. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  20087. }
  20088. };
  20089. // To get accurate point with reference to
  20090. // entire path distance at time t,
  20091. // following has to be done:
  20092. // 1. Length of each sub path have to be known
  20093. // 2. Locate and identify type of curve
  20094. // 3. Get t for the curve
  20095. // 4. Return curve.getPointAt(t')
  20096. THREE.CurvePath.prototype.getPoint = function( t ) {
  20097. var d = t * this.getLength();
  20098. var curveLengths = this.getCurveLengths();
  20099. var i = 0;
  20100. // To think about boundaries points.
  20101. while ( i < curveLengths.length ) {
  20102. if ( curveLengths[ i ] >= d ) {
  20103. var diff = curveLengths[ i ] - d;
  20104. var curve = this.curves[ i ];
  20105. var u = 1 - diff / curve.getLength();
  20106. return curve.getPointAt( u );
  20107. }
  20108. i ++;
  20109. }
  20110. return null;
  20111. // loop where sum != 0, sum > d , sum+1 <d
  20112. };
  20113. /*
  20114. THREE.CurvePath.prototype.getTangent = function( t ) {
  20115. };
  20116. */
  20117. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20118. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20119. // getPoint() depends on getLength
  20120. THREE.CurvePath.prototype.getLength = function() {
  20121. var lens = this.getCurveLengths();
  20122. return lens[ lens.length - 1 ];
  20123. };
  20124. // Compute lengths and cache them
  20125. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20126. THREE.CurvePath.prototype.getCurveLengths = function() {
  20127. // We use cache values if curves and cache array are same length
  20128. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20129. return this.cacheLengths;
  20130. }
  20131. // Get length of sub-curve
  20132. // Push sums into cached array
  20133. var lengths = [], sums = 0;
  20134. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20135. sums += this.curves[ i ].getLength();
  20136. lengths.push( sums );
  20137. }
  20138. this.cacheLengths = lengths;
  20139. return lengths;
  20140. };
  20141. /**************************************************************
  20142. * Create Geometries Helpers
  20143. **************************************************************/
  20144. /// Generate geometry from path points (for Line or Points objects)
  20145. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20146. var pts = this.getPoints( divisions, true );
  20147. return this.createGeometry( pts );
  20148. };
  20149. // Generate geometry from equidistant sampling along the path
  20150. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20151. var pts = this.getSpacedPoints( divisions, true );
  20152. return this.createGeometry( pts );
  20153. };
  20154. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20155. var geometry = new THREE.Geometry();
  20156. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20157. var point = points[ i ];
  20158. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20159. }
  20160. return geometry;
  20161. };
  20162. // File:src/extras/core/Path.js
  20163. /**
  20164. * @author zz85 / http://www.lab4games.net/zz85/blog
  20165. * Creates free form 2d path using series of points, lines or curves.
  20166. *
  20167. **/
  20168. THREE.Path = function ( points ) {
  20169. THREE.CurvePath.call( this );
  20170. this.actions = [];
  20171. if ( points ) {
  20172. this.fromPoints( points );
  20173. }
  20174. };
  20175. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20176. THREE.Path.prototype.constructor = THREE.Path;
  20177. // TODO Clean up PATH API
  20178. // Create path using straight lines to connect all points
  20179. // - vectors: array of Vector2
  20180. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20181. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20182. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20183. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20184. }
  20185. };
  20186. // startPath() endPath()?
  20187. THREE.Path.prototype.moveTo = function ( x, y ) {
  20188. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20189. };
  20190. THREE.Path.prototype.lineTo = function ( x, y ) {
  20191. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20192. var x0 = lastargs[ lastargs.length - 2 ];
  20193. var y0 = lastargs[ lastargs.length - 1 ];
  20194. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20195. this.curves.push( curve );
  20196. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20197. };
  20198. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20199. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20200. var x0 = lastargs[ lastargs.length - 2 ];
  20201. var y0 = lastargs[ lastargs.length - 1 ];
  20202. var curve = new THREE.QuadraticBezierCurve(
  20203. new THREE.Vector2( x0, y0 ),
  20204. new THREE.Vector2( aCPx, aCPy ),
  20205. new THREE.Vector2( aX, aY )
  20206. );
  20207. this.curves.push( curve );
  20208. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20209. };
  20210. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20211. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20212. var x0 = lastargs[ lastargs.length - 2 ];
  20213. var y0 = lastargs[ lastargs.length - 1 ];
  20214. var curve = new THREE.CubicBezierCurve(
  20215. new THREE.Vector2( x0, y0 ),
  20216. new THREE.Vector2( aCP1x, aCP1y ),
  20217. new THREE.Vector2( aCP2x, aCP2y ),
  20218. new THREE.Vector2( aX, aY )
  20219. );
  20220. this.curves.push( curve );
  20221. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20222. };
  20223. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20224. var args = Array.prototype.slice.call( arguments );
  20225. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20226. var x0 = lastargs[ lastargs.length - 2 ];
  20227. var y0 = lastargs[ lastargs.length - 1 ];
  20228. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20229. Array.prototype.push.apply( npts, pts );
  20230. var curve = new THREE.SplineCurve( npts );
  20231. this.curves.push( curve );
  20232. this.actions.push( { action: 'splineThru', args: args } );
  20233. };
  20234. // FUTURE: Change the API or follow canvas API?
  20235. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20236. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20237. var x0 = lastargs[ lastargs.length - 2 ];
  20238. var y0 = lastargs[ lastargs.length - 1 ];
  20239. this.absarc( aX + x0, aY + y0, aRadius,
  20240. aStartAngle, aEndAngle, aClockwise );
  20241. };
  20242. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20243. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20244. };
  20245. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20246. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20247. var x0 = lastargs[ lastargs.length - 2 ];
  20248. var y0 = lastargs[ lastargs.length - 1 ];
  20249. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20250. };
  20251. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20252. var args = [
  20253. aX, aY,
  20254. xRadius, yRadius,
  20255. aStartAngle, aEndAngle,
  20256. aClockwise,
  20257. aRotation || 0 // aRotation is optional.
  20258. ];
  20259. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20260. this.curves.push( curve );
  20261. var lastPoint = curve.getPoint( 1 );
  20262. args.push( lastPoint.x );
  20263. args.push( lastPoint.y );
  20264. this.actions.push( { action: 'ellipse', args: args } );
  20265. };
  20266. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  20267. if ( ! divisions ) divisions = 40;
  20268. var points = [];
  20269. for ( var i = 0; i < divisions; i ++ ) {
  20270. points.push( this.getPoint( i / divisions ) );
  20271. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  20272. }
  20273. // if ( closedPath ) {
  20274. //
  20275. // points.push( points[ 0 ] );
  20276. //
  20277. // }
  20278. return points;
  20279. };
  20280. /* Return an array of vectors based on contour of the path */
  20281. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  20282. divisions = divisions || 12;
  20283. var b2 = THREE.ShapeUtils.b2;
  20284. var b3 = THREE.ShapeUtils.b3;
  20285. var points = [];
  20286. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  20287. laste, tx, ty;
  20288. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  20289. var item = this.actions[ i ];
  20290. var action = item.action;
  20291. var args = item.args;
  20292. switch ( action ) {
  20293. case 'moveTo':
  20294. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20295. break;
  20296. case 'lineTo':
  20297. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20298. break;
  20299. case 'quadraticCurveTo':
  20300. cpx = args[ 2 ];
  20301. cpy = args[ 3 ];
  20302. cpx1 = args[ 0 ];
  20303. cpy1 = args[ 1 ];
  20304. if ( points.length > 0 ) {
  20305. laste = points[ points.length - 1 ];
  20306. cpx0 = laste.x;
  20307. cpy0 = laste.y;
  20308. } else {
  20309. laste = this.actions[ i - 1 ].args;
  20310. cpx0 = laste[ laste.length - 2 ];
  20311. cpy0 = laste[ laste.length - 1 ];
  20312. }
  20313. for ( var j = 1; j <= divisions; j ++ ) {
  20314. var t = j / divisions;
  20315. tx = b2( t, cpx0, cpx1, cpx );
  20316. ty = b2( t, cpy0, cpy1, cpy );
  20317. points.push( new THREE.Vector2( tx, ty ) );
  20318. }
  20319. break;
  20320. case 'bezierCurveTo':
  20321. cpx = args[ 4 ];
  20322. cpy = args[ 5 ];
  20323. cpx1 = args[ 0 ];
  20324. cpy1 = args[ 1 ];
  20325. cpx2 = args[ 2 ];
  20326. cpy2 = args[ 3 ];
  20327. if ( points.length > 0 ) {
  20328. laste = points[ points.length - 1 ];
  20329. cpx0 = laste.x;
  20330. cpy0 = laste.y;
  20331. } else {
  20332. laste = this.actions[ i - 1 ].args;
  20333. cpx0 = laste[ laste.length - 2 ];
  20334. cpy0 = laste[ laste.length - 1 ];
  20335. }
  20336. for ( var j = 1; j <= divisions; j ++ ) {
  20337. var t = j / divisions;
  20338. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  20339. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  20340. points.push( new THREE.Vector2( tx, ty ) );
  20341. }
  20342. break;
  20343. case 'splineThru':
  20344. laste = this.actions[ i - 1 ].args;
  20345. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  20346. var spts = [ last ];
  20347. var n = divisions * args[ 0 ].length;
  20348. spts = spts.concat( args[ 0 ] );
  20349. var spline = new THREE.SplineCurve( spts );
  20350. for ( var j = 1; j <= n; j ++ ) {
  20351. points.push( spline.getPointAt( j / n ) );
  20352. }
  20353. break;
  20354. case 'arc':
  20355. var aX = args[ 0 ], aY = args[ 1 ],
  20356. aRadius = args[ 2 ],
  20357. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  20358. aClockwise = !! args[ 5 ];
  20359. var deltaAngle = aEndAngle - aStartAngle;
  20360. var angle;
  20361. var tdivisions = divisions * 2;
  20362. for ( var j = 1; j <= tdivisions; j ++ ) {
  20363. var t = j / tdivisions;
  20364. if ( ! aClockwise ) {
  20365. t = 1 - t;
  20366. }
  20367. angle = aStartAngle + t * deltaAngle;
  20368. tx = aX + aRadius * Math.cos( angle );
  20369. ty = aY + aRadius * Math.sin( angle );
  20370. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20371. points.push( new THREE.Vector2( tx, ty ) );
  20372. }
  20373. //console.log(points);
  20374. break;
  20375. case 'ellipse':
  20376. var aX = args[ 0 ], aY = args[ 1 ],
  20377. xRadius = args[ 2 ],
  20378. yRadius = args[ 3 ],
  20379. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  20380. aClockwise = !! args[ 6 ],
  20381. aRotation = args[ 7 ];
  20382. var deltaAngle = aEndAngle - aStartAngle;
  20383. var angle;
  20384. var tdivisions = divisions * 2;
  20385. var cos, sin;
  20386. if ( aRotation !== 0 ) {
  20387. cos = Math.cos( aRotation );
  20388. sin = Math.sin( aRotation );
  20389. }
  20390. for ( var j = 1; j <= tdivisions; j ++ ) {
  20391. var t = j / tdivisions;
  20392. if ( ! aClockwise ) {
  20393. t = 1 - t;
  20394. }
  20395. angle = aStartAngle + t * deltaAngle;
  20396. tx = aX + xRadius * Math.cos( angle );
  20397. ty = aY + yRadius * Math.sin( angle );
  20398. if ( aRotation !== 0 ) {
  20399. var x = tx, y = ty;
  20400. // Rotate the point about the center of the ellipse.
  20401. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  20402. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  20403. }
  20404. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20405. points.push( new THREE.Vector2( tx, ty ) );
  20406. }
  20407. //console.log(points);
  20408. break;
  20409. } // end switch
  20410. }
  20411. // Normalize to remove the closing point by default.
  20412. var lastPoint = points[ points.length - 1 ];
  20413. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  20414. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  20415. points.splice( points.length - 1, 1 );
  20416. if ( closedPath ) {
  20417. points.push( points[ 0 ] );
  20418. }
  20419. return points;
  20420. };
  20421. //
  20422. // Breaks path into shapes
  20423. //
  20424. // Assumptions (if parameter isCCW==true the opposite holds):
  20425. // - solid shapes are defined clockwise (CW)
  20426. // - holes are defined counterclockwise (CCW)
  20427. //
  20428. // If parameter noHoles==true:
  20429. // - all subPaths are regarded as solid shapes
  20430. // - definition order CW/CCW has no relevance
  20431. //
  20432. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  20433. function extractSubpaths( inActions ) {
  20434. var subPaths = [], lastPath = new THREE.Path();
  20435. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  20436. var item = inActions[ i ];
  20437. var args = item.args;
  20438. var action = item.action;
  20439. if ( action === 'moveTo' ) {
  20440. if ( lastPath.actions.length !== 0 ) {
  20441. subPaths.push( lastPath );
  20442. lastPath = new THREE.Path();
  20443. }
  20444. }
  20445. lastPath[ action ].apply( lastPath, args );
  20446. }
  20447. if ( lastPath.actions.length !== 0 ) {
  20448. subPaths.push( lastPath );
  20449. }
  20450. // console.log(subPaths);
  20451. return subPaths;
  20452. }
  20453. function toShapesNoHoles( inSubpaths ) {
  20454. var shapes = [];
  20455. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20456. var tmpPath = inSubpaths[ i ];
  20457. var tmpShape = new THREE.Shape();
  20458. tmpShape.actions = tmpPath.actions;
  20459. tmpShape.curves = tmpPath.curves;
  20460. shapes.push( tmpShape );
  20461. }
  20462. //console.log("shape", shapes);
  20463. return shapes;
  20464. }
  20465. function isPointInsidePolygon( inPt, inPolygon ) {
  20466. var polyLen = inPolygon.length;
  20467. // inPt on polygon contour => immediate success or
  20468. // toggling of inside/outside at every single! intersection point of an edge
  20469. // with the horizontal line through inPt, left of inPt
  20470. // not counting lowerY endpoints of edges and whole edges on that line
  20471. var inside = false;
  20472. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20473. var edgeLowPt = inPolygon[ p ];
  20474. var edgeHighPt = inPolygon[ q ];
  20475. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20476. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20477. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20478. // not parallel
  20479. if ( edgeDy < 0 ) {
  20480. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20481. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20482. }
  20483. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20484. if ( inPt.y === edgeLowPt.y ) {
  20485. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20486. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20487. } else {
  20488. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20489. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20490. if ( perpEdge < 0 ) continue;
  20491. inside = ! inside; // true intersection left of inPt
  20492. }
  20493. } else {
  20494. // parallel or collinear
  20495. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20496. // edge lies on the same horizontal line as inPt
  20497. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20498. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20499. // continue;
  20500. }
  20501. }
  20502. return inside;
  20503. }
  20504. var isClockWise = THREE.ShapeUtils.isClockWise;
  20505. var subPaths = extractSubpaths( this.actions );
  20506. if ( subPaths.length === 0 ) return [];
  20507. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20508. var solid, tmpPath, tmpShape, shapes = [];
  20509. if ( subPaths.length === 1 ) {
  20510. tmpPath = subPaths[ 0 ];
  20511. tmpShape = new THREE.Shape();
  20512. tmpShape.actions = tmpPath.actions;
  20513. tmpShape.curves = tmpPath.curves;
  20514. shapes.push( tmpShape );
  20515. return shapes;
  20516. }
  20517. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20518. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20519. // console.log("Holes first", holesFirst);
  20520. var betterShapeHoles = [];
  20521. var newShapes = [];
  20522. var newShapeHoles = [];
  20523. var mainIdx = 0;
  20524. var tmpPoints;
  20525. newShapes[ mainIdx ] = undefined;
  20526. newShapeHoles[ mainIdx ] = [];
  20527. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20528. tmpPath = subPaths[ i ];
  20529. tmpPoints = tmpPath.getPoints();
  20530. solid = isClockWise( tmpPoints );
  20531. solid = isCCW ? ! solid : solid;
  20532. if ( solid ) {
  20533. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20534. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  20535. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  20536. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20537. if ( holesFirst ) mainIdx ++;
  20538. newShapeHoles[ mainIdx ] = [];
  20539. //console.log('cw', i);
  20540. } else {
  20541. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20542. //console.log('ccw', i);
  20543. }
  20544. }
  20545. // only Holes? -> probably all Shapes with wrong orientation
  20546. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20547. if ( newShapes.length > 1 ) {
  20548. var ambiguous = false;
  20549. var toChange = [];
  20550. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20551. betterShapeHoles[ sIdx ] = [];
  20552. }
  20553. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20554. var sho = newShapeHoles[ sIdx ];
  20555. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20556. var ho = sho[ hIdx ];
  20557. var hole_unassigned = true;
  20558. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20559. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20560. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20561. if ( hole_unassigned ) {
  20562. hole_unassigned = false;
  20563. betterShapeHoles[ s2Idx ].push( ho );
  20564. } else {
  20565. ambiguous = true;
  20566. }
  20567. }
  20568. }
  20569. if ( hole_unassigned ) {
  20570. betterShapeHoles[ sIdx ].push( ho );
  20571. }
  20572. }
  20573. }
  20574. // console.log("ambiguous: ", ambiguous);
  20575. if ( toChange.length > 0 ) {
  20576. // console.log("to change: ", toChange);
  20577. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20578. }
  20579. }
  20580. var tmpHoles;
  20581. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20582. tmpShape = newShapes[ i ].s;
  20583. shapes.push( tmpShape );
  20584. tmpHoles = newShapeHoles[ i ];
  20585. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20586. tmpShape.holes.push( tmpHoles[ j ].h );
  20587. }
  20588. }
  20589. //console.log("shape", shapes);
  20590. return shapes;
  20591. };
  20592. // File:src/extras/core/Shape.js
  20593. /**
  20594. * @author zz85 / http://www.lab4games.net/zz85/blog
  20595. * Defines a 2d shape plane using paths.
  20596. **/
  20597. // STEP 1 Create a path.
  20598. // STEP 2 Turn path into shape.
  20599. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20600. // STEP 3a - Extract points from each shape, turn to vertices
  20601. // STEP 3b - Triangulate each shape, add faces.
  20602. THREE.Shape = function () {
  20603. THREE.Path.apply( this, arguments );
  20604. this.holes = [];
  20605. };
  20606. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  20607. THREE.Shape.prototype.constructor = THREE.Shape;
  20608. // Convenience method to return ExtrudeGeometry
  20609. THREE.Shape.prototype.extrude = function ( options ) {
  20610. return new THREE.ExtrudeGeometry( this, options );
  20611. };
  20612. // Convenience method to return ShapeGeometry
  20613. THREE.Shape.prototype.makeGeometry = function ( options ) {
  20614. return new THREE.ShapeGeometry( this, options );
  20615. };
  20616. // Get points of holes
  20617. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  20618. var holesPts = [];
  20619. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20620. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20621. }
  20622. return holesPts;
  20623. };
  20624. // Get points of shape and holes (keypoints based on segments parameter)
  20625. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  20626. return {
  20627. shape: this.getPoints( divisions ),
  20628. holes: this.getPointsHoles( divisions )
  20629. };
  20630. };
  20631. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  20632. return this.extractAllPoints( divisions );
  20633. };
  20634. THREE.Shape.Utils = THREE.ShapeUtils; // backwards compatibility
  20635. // File:src/extras/curves/LineCurve.js
  20636. /**************************************************************
  20637. * Line
  20638. **************************************************************/
  20639. THREE.LineCurve = function ( v1, v2 ) {
  20640. this.v1 = v1;
  20641. this.v2 = v2;
  20642. };
  20643. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  20644. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  20645. THREE.LineCurve.prototype.getPoint = function ( t ) {
  20646. var point = this.v2.clone().sub( this.v1 );
  20647. point.multiplyScalar( t ).add( this.v1 );
  20648. return point;
  20649. };
  20650. // Line curve is linear, so we can overwrite default getPointAt
  20651. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  20652. return this.getPoint( u );
  20653. };
  20654. THREE.LineCurve.prototype.getTangent = function( t ) {
  20655. var tangent = this.v2.clone().sub( this.v1 );
  20656. return tangent.normalize();
  20657. };
  20658. // File:src/extras/curves/QuadraticBezierCurve.js
  20659. /**************************************************************
  20660. * Quadratic Bezier curve
  20661. **************************************************************/
  20662. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  20663. this.v0 = v0;
  20664. this.v1 = v1;
  20665. this.v2 = v2;
  20666. };
  20667. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20668. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  20669. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20670. var b2 = THREE.ShapeUtils.b2;
  20671. return new THREE.Vector2(
  20672. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20673. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20674. );
  20675. };
  20676. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20677. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  20678. return new THREE.Vector2(
  20679. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20680. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20681. ).normalize();
  20682. };
  20683. // File:src/extras/curves/CubicBezierCurve.js
  20684. /**************************************************************
  20685. * Cubic Bezier curve
  20686. **************************************************************/
  20687. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  20688. this.v0 = v0;
  20689. this.v1 = v1;
  20690. this.v2 = v2;
  20691. this.v3 = v3;
  20692. };
  20693. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20694. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  20695. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  20696. var b3 = THREE.ShapeUtils.b3;
  20697. return new THREE.Vector2(
  20698. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20699. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20700. );
  20701. };
  20702. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  20703. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  20704. return new THREE.Vector2(
  20705. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20706. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20707. ).normalize();
  20708. };
  20709. // File:src/extras/curves/SplineCurve.js
  20710. /**************************************************************
  20711. * Spline curve
  20712. **************************************************************/
  20713. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  20714. this.points = ( points == undefined ) ? [] : points;
  20715. };
  20716. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  20717. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  20718. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  20719. var points = this.points;
  20720. var point = ( points.length - 1 ) * t;
  20721. var intPoint = Math.floor( point );
  20722. var weight = point - intPoint;
  20723. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20724. var point1 = points[ intPoint ];
  20725. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20726. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20727. var interpolate = THREE.CurveUtils.interpolate;
  20728. return new THREE.Vector2(
  20729. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20730. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20731. );
  20732. };
  20733. // File:src/extras/curves/EllipseCurve.js
  20734. /**************************************************************
  20735. * Ellipse curve
  20736. **************************************************************/
  20737. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20738. this.aX = aX;
  20739. this.aY = aY;
  20740. this.xRadius = xRadius;
  20741. this.yRadius = yRadius;
  20742. this.aStartAngle = aStartAngle;
  20743. this.aEndAngle = aEndAngle;
  20744. this.aClockwise = aClockwise;
  20745. this.aRotation = aRotation || 0;
  20746. };
  20747. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  20748. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  20749. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  20750. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20751. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  20752. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  20753. var angle;
  20754. if ( this.aClockwise === true ) {
  20755. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  20756. } else {
  20757. angle = this.aStartAngle + t * deltaAngle;
  20758. }
  20759. var x = this.aX + this.xRadius * Math.cos( angle );
  20760. var y = this.aY + this.yRadius * Math.sin( angle );
  20761. if ( this.aRotation !== 0 ) {
  20762. var cos = Math.cos( this.aRotation );
  20763. var sin = Math.sin( this.aRotation );
  20764. var tx = x, ty = y;
  20765. // Rotate the point about the center of the ellipse.
  20766. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  20767. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  20768. }
  20769. return new THREE.Vector2( x, y );
  20770. };
  20771. // File:src/extras/curves/ArcCurve.js
  20772. /**************************************************************
  20773. * Arc curve
  20774. **************************************************************/
  20775. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20776. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20777. };
  20778. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  20779. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  20780. // File:src/extras/curves/LineCurve3.js
  20781. /**************************************************************
  20782. * Line3D
  20783. **************************************************************/
  20784. THREE.LineCurve3 = THREE.Curve.create(
  20785. function ( v1, v2 ) {
  20786. this.v1 = v1;
  20787. this.v2 = v2;
  20788. },
  20789. function ( t ) {
  20790. var vector = new THREE.Vector3();
  20791. vector.subVectors( this.v2, this.v1 ); // diff
  20792. vector.multiplyScalar( t );
  20793. vector.add( this.v1 );
  20794. return vector;
  20795. }
  20796. );
  20797. // File:src/extras/curves/QuadraticBezierCurve3.js
  20798. /**************************************************************
  20799. * Quadratic Bezier 3D curve
  20800. **************************************************************/
  20801. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  20802. function ( v0, v1, v2 ) {
  20803. this.v0 = v0;
  20804. this.v1 = v1;
  20805. this.v2 = v2;
  20806. },
  20807. function ( t ) {
  20808. var b2 = THREE.ShapeUtils.b2;
  20809. return new THREE.Vector3(
  20810. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20811. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  20812. b2( t, this.v0.z, this.v1.z, this.v2.z )
  20813. );
  20814. }
  20815. );
  20816. // File:src/extras/curves/CubicBezierCurve3.js
  20817. /**************************************************************
  20818. * Cubic Bezier 3D curve
  20819. **************************************************************/
  20820. THREE.CubicBezierCurve3 = THREE.Curve.create(
  20821. function ( v0, v1, v2, v3 ) {
  20822. this.v0 = v0;
  20823. this.v1 = v1;
  20824. this.v2 = v2;
  20825. this.v3 = v3;
  20826. },
  20827. function ( t ) {
  20828. var b3 = THREE.ShapeUtils.b3;
  20829. return new THREE.Vector3(
  20830. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20831. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  20832. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  20833. );
  20834. }
  20835. );
  20836. // File:src/extras/curves/SplineCurve3.js
  20837. /**************************************************************
  20838. * Spline 3D curve
  20839. **************************************************************/
  20840. THREE.SplineCurve3 = THREE.Curve.create(
  20841. function ( points /* array of Vector3 */ ) {
  20842. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  20843. this.points = ( points == undefined ) ? [] : points;
  20844. },
  20845. function ( t ) {
  20846. var points = this.points;
  20847. var point = ( points.length - 1 ) * t;
  20848. var intPoint = Math.floor( point );
  20849. var weight = point - intPoint;
  20850. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  20851. var point1 = points[ intPoint ];
  20852. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20853. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20854. var interpolate = THREE.CurveUtils.interpolate;
  20855. return new THREE.Vector3(
  20856. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20857. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  20858. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  20859. );
  20860. }
  20861. );
  20862. // File:src/extras/curves/CatmullRomCurve3.js
  20863. /**
  20864. * @author zz85 https://github.com/zz85
  20865. *
  20866. * Centripetal CatmullRom Curve - which is useful for avoiding
  20867. * cusps and self-intersections in non-uniform catmull rom curves.
  20868. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20869. *
  20870. * curve.type accepts centripetal(default), chordal and catmullrom
  20871. * curve.tension is used for catmullrom which defaults to 0.5
  20872. */
  20873. THREE.CatmullRomCurve3 = ( function() {
  20874. var
  20875. tmp = new THREE.Vector3(),
  20876. px = new CubicPoly(),
  20877. py = new CubicPoly(),
  20878. pz = new CubicPoly();
  20879. /*
  20880. Based on an optimized c++ solution in
  20881. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20882. - http://ideone.com/NoEbVM
  20883. This CubicPoly class could be used for reusing some variables and calculations,
  20884. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20885. which can be placed in CurveUtils.
  20886. */
  20887. function CubicPoly() {
  20888. }
  20889. /*
  20890. * Compute coefficients for a cubic polynomial
  20891. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20892. * such that
  20893. * p(0) = x0, p(1) = x1
  20894. * and
  20895. * p'(0) = t0, p'(1) = t1.
  20896. */
  20897. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  20898. this.c0 = x0;
  20899. this.c1 = t0;
  20900. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20901. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20902. };
  20903. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20904. // compute tangents when parameterized in [t1,t2]
  20905. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20906. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20907. // rescale tangents for parametrization in [0,1]
  20908. t1 *= dt1;
  20909. t2 *= dt1;
  20910. // initCubicPoly
  20911. this.init( x1, x2, t1, t2 );
  20912. };
  20913. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  20914. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  20915. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20916. };
  20917. CubicPoly.prototype.calc = function( t ) {
  20918. var t2 = t * t;
  20919. var t3 = t2 * t;
  20920. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  20921. };
  20922. // Subclass Three.js curve
  20923. return THREE.Curve.create(
  20924. function ( p /* array of Vector3 */ ) {
  20925. this.points = p || [];
  20926. },
  20927. function ( t ) {
  20928. var points = this.points,
  20929. point, intPoint, weight, l;
  20930. l = points.length;
  20931. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  20932. point = ( l - 1 ) * t;
  20933. intPoint = Math.floor( point );
  20934. weight = point - intPoint;
  20935. if ( weight === 0 && intPoint === l - 1 ) {
  20936. intPoint = l - 2;
  20937. weight = 1;
  20938. }
  20939. var p0, p1, p2, p3;
  20940. if ( intPoint === 0 ) {
  20941. // extrapolate first point
  20942. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  20943. p0 = tmp;
  20944. } else {
  20945. p0 = points[ intPoint - 1 ];
  20946. }
  20947. p1 = points[ intPoint ];
  20948. p2 = points[ intPoint + 1 ];
  20949. if ( intPoint + 2 < l ) {
  20950. p3 = points[ intPoint + 2 ]
  20951. } else {
  20952. // extrapolate last point
  20953. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  20954. p3 = tmp;
  20955. }
  20956. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  20957. // init Centripetal / Chordal Catmull-Rom
  20958. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  20959. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  20960. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  20961. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  20962. // safety check for repeated points
  20963. if ( dt1 < 1e-4 ) dt1 = 1.0;
  20964. if ( dt0 < 1e-4 ) dt0 = dt1;
  20965. if ( dt2 < 1e-4 ) dt2 = dt1;
  20966. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  20967. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  20968. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  20969. } else if ( this.type === 'catmullrom' ) {
  20970. var tension = this.tension !== undefined ? this.tension : 0.5;
  20971. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  20972. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  20973. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  20974. }
  20975. var v = new THREE.Vector3(
  20976. px.calc( weight ),
  20977. py.calc( weight ),
  20978. pz.calc( weight )
  20979. );
  20980. return v;
  20981. }
  20982. );
  20983. } )();
  20984. // File:src/extras/curves/ClosedSplineCurve3.js
  20985. /**************************************************************
  20986. * Closed Spline 3D curve
  20987. **************************************************************/
  20988. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  20989. function ( points /* array of Vector3 */ ) {
  20990. this.points = ( points == undefined ) ? [] : points;
  20991. },
  20992. function ( t ) {
  20993. var points = this.points;
  20994. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  20995. var intPoint = Math.floor( point );
  20996. var weight = point - intPoint;
  20997. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  20998. var point0 = points[ ( intPoint - 1 ) % points.length ];
  20999. var point1 = points[ ( intPoint ) % points.length ];
  21000. var point2 = points[ ( intPoint + 1 ) % points.length ];
  21001. var point3 = points[ ( intPoint + 2 ) % points.length ];
  21002. var interpolate = THREE.CurveUtils.interpolate;
  21003. return new THREE.Vector3(
  21004. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21005. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  21006. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21007. );
  21008. }
  21009. );
  21010. // File:src/extras/geometries/BoxGeometry.js
  21011. /**
  21012. * @author mrdoob / http://mrdoob.com/
  21013. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21014. */
  21015. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21016. THREE.Geometry.call( this );
  21017. this.type = 'BoxGeometry';
  21018. this.parameters = {
  21019. width: width,
  21020. height: height,
  21021. depth: depth,
  21022. widthSegments: widthSegments,
  21023. heightSegments: heightSegments,
  21024. depthSegments: depthSegments
  21025. };
  21026. this.widthSegments = widthSegments || 1;
  21027. this.heightSegments = heightSegments || 1;
  21028. this.depthSegments = depthSegments || 1;
  21029. var scope = this;
  21030. var width_half = width / 2;
  21031. var height_half = height / 2;
  21032. var depth_half = depth / 2;
  21033. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  21034. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  21035. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  21036. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  21037. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  21038. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  21039. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  21040. var w, ix, iy,
  21041. gridX = scope.widthSegments,
  21042. gridY = scope.heightSegments,
  21043. width_half = width / 2,
  21044. height_half = height / 2,
  21045. offset = scope.vertices.length;
  21046. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  21047. w = 'z';
  21048. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  21049. w = 'y';
  21050. gridY = scope.depthSegments;
  21051. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  21052. w = 'x';
  21053. gridX = scope.depthSegments;
  21054. }
  21055. var gridX1 = gridX + 1,
  21056. gridY1 = gridY + 1,
  21057. segment_width = width / gridX,
  21058. segment_height = height / gridY,
  21059. normal = new THREE.Vector3();
  21060. normal[ w ] = depth > 0 ? 1 : - 1;
  21061. for ( iy = 0; iy < gridY1; iy ++ ) {
  21062. for ( ix = 0; ix < gridX1; ix ++ ) {
  21063. var vector = new THREE.Vector3();
  21064. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  21065. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  21066. vector[ w ] = depth;
  21067. scope.vertices.push( vector );
  21068. }
  21069. }
  21070. for ( iy = 0; iy < gridY; iy ++ ) {
  21071. for ( ix = 0; ix < gridX; ix ++ ) {
  21072. var a = ix + gridX1 * iy;
  21073. var b = ix + gridX1 * ( iy + 1 );
  21074. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21075. var d = ( ix + 1 ) + gridX1 * iy;
  21076. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  21077. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  21078. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  21079. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  21080. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  21081. face.normal.copy( normal );
  21082. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21083. face.materialIndex = materialIndex;
  21084. scope.faces.push( face );
  21085. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  21086. face = new THREE.Face3( b + offset, c + offset, d + offset );
  21087. face.normal.copy( normal );
  21088. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21089. face.materialIndex = materialIndex;
  21090. scope.faces.push( face );
  21091. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  21092. }
  21093. }
  21094. }
  21095. this.mergeVertices();
  21096. };
  21097. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21098. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  21099. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  21100. // File:src/extras/geometries/CircleGeometry.js
  21101. /**
  21102. * @author hughes
  21103. */
  21104. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21105. THREE.Geometry.call( this );
  21106. this.type = 'CircleGeometry';
  21107. this.parameters = {
  21108. radius: radius,
  21109. segments: segments,
  21110. thetaStart: thetaStart,
  21111. thetaLength: thetaLength
  21112. };
  21113. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21114. };
  21115. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21116. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21117. // File:src/extras/geometries/CircleBufferGeometry.js
  21118. /**
  21119. * @author benaadams / https://twitter.com/ben_a_adams
  21120. */
  21121. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21122. THREE.BufferGeometry.call( this );
  21123. this.type = 'CircleBufferGeometry';
  21124. this.parameters = {
  21125. radius: radius,
  21126. segments: segments,
  21127. thetaStart: thetaStart,
  21128. thetaLength: thetaLength
  21129. };
  21130. radius = radius || 50;
  21131. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21132. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21133. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21134. var vertices = segments + 2;
  21135. var positions = new Float32Array( vertices * 3 );
  21136. var normals = new Float32Array( vertices * 3 );
  21137. var uvs = new Float32Array( vertices * 2 );
  21138. // center data is already zero, but need to set a few extras
  21139. normals[ 2 ] = 1.0;
  21140. uvs[ 0 ] = 0.5;
  21141. uvs[ 1 ] = 0.5;
  21142. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21143. var segment = thetaStart + s / segments * thetaLength;
  21144. positions[ i ] = radius * Math.cos( segment );
  21145. positions[ i + 1 ] = radius * Math.sin( segment );
  21146. normals[ i + 2 ] = 1; // normal z
  21147. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21148. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21149. }
  21150. var indices = [];
  21151. for ( var i = 1; i <= segments; i ++ ) {
  21152. indices.push( i, i + 1, 0 );
  21153. }
  21154. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21155. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21156. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21157. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21158. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21159. };
  21160. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21161. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21162. // File:src/extras/geometries/CylinderGeometry.js
  21163. /**
  21164. * @author mrdoob / http://mrdoob.com/
  21165. */
  21166. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21167. THREE.Geometry.call( this );
  21168. this.type = 'CylinderGeometry';
  21169. this.parameters = {
  21170. radiusTop: radiusTop,
  21171. radiusBottom: radiusBottom,
  21172. height: height,
  21173. radialSegments: radialSegments,
  21174. heightSegments: heightSegments,
  21175. openEnded: openEnded,
  21176. thetaStart: thetaStart,
  21177. thetaLength: thetaLength
  21178. };
  21179. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21180. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21181. height = height !== undefined ? height : 100;
  21182. radialSegments = radialSegments || 8;
  21183. heightSegments = heightSegments || 1;
  21184. openEnded = openEnded !== undefined ? openEnded : false;
  21185. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21186. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  21187. var heightHalf = height / 2;
  21188. var x, y, vertices = [], uvs = [];
  21189. for ( y = 0; y <= heightSegments; y ++ ) {
  21190. var verticesRow = [];
  21191. var uvsRow = [];
  21192. var v = y / heightSegments;
  21193. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21194. for ( x = 0; x <= radialSegments; x ++ ) {
  21195. var u = x / radialSegments;
  21196. var vertex = new THREE.Vector3();
  21197. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21198. vertex.y = - v * height + heightHalf;
  21199. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21200. this.vertices.push( vertex );
  21201. verticesRow.push( this.vertices.length - 1 );
  21202. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  21203. }
  21204. vertices.push( verticesRow );
  21205. uvs.push( uvsRow );
  21206. }
  21207. var tanTheta = ( radiusBottom - radiusTop ) / height;
  21208. var na, nb;
  21209. for ( x = 0; x < radialSegments; x ++ ) {
  21210. if ( radiusTop !== 0 ) {
  21211. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  21212. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  21213. } else {
  21214. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  21215. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  21216. }
  21217. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  21218. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  21219. for ( y = 0; y < heightSegments; y ++ ) {
  21220. var v1 = vertices[ y ][ x ];
  21221. var v2 = vertices[ y + 1 ][ x ];
  21222. var v3 = vertices[ y + 1 ][ x + 1 ];
  21223. var v4 = vertices[ y ][ x + 1 ];
  21224. var n1 = na.clone();
  21225. var n2 = na.clone();
  21226. var n3 = nb.clone();
  21227. var n4 = nb.clone();
  21228. var uv1 = uvs[ y ][ x ].clone();
  21229. var uv2 = uvs[ y + 1 ][ x ].clone();
  21230. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  21231. var uv4 = uvs[ y ][ x + 1 ].clone();
  21232. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  21233. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  21234. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  21235. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  21236. }
  21237. }
  21238. // top cap
  21239. if ( openEnded === false && radiusTop > 0 ) {
  21240. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  21241. for ( x = 0; x < radialSegments; x ++ ) {
  21242. var v1 = vertices[ 0 ][ x ];
  21243. var v2 = vertices[ 0 ][ x + 1 ];
  21244. var v3 = this.vertices.length - 1;
  21245. var n1 = new THREE.Vector3( 0, 1, 0 );
  21246. var n2 = new THREE.Vector3( 0, 1, 0 );
  21247. var n3 = new THREE.Vector3( 0, 1, 0 );
  21248. var uv1 = uvs[ 0 ][ x ].clone();
  21249. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  21250. var uv3 = new THREE.Vector2( uv2.x, 0 );
  21251. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 1 ) );
  21252. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21253. }
  21254. }
  21255. // bottom cap
  21256. if ( openEnded === false && radiusBottom > 0 ) {
  21257. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  21258. for ( x = 0; x < radialSegments; x ++ ) {
  21259. var v1 = vertices[ heightSegments ][ x + 1 ];
  21260. var v2 = vertices[ heightSegments ][ x ];
  21261. var v3 = this.vertices.length - 1;
  21262. var n1 = new THREE.Vector3( 0, - 1, 0 );
  21263. var n2 = new THREE.Vector3( 0, - 1, 0 );
  21264. var n3 = new THREE.Vector3( 0, - 1, 0 );
  21265. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  21266. var uv2 = uvs[ heightSegments ][ x ].clone();
  21267. var uv3 = new THREE.Vector2( uv2.x, 1 );
  21268. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 2 ) );
  21269. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21270. }
  21271. }
  21272. this.computeFaceNormals();
  21273. };
  21274. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21275. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  21276. // File:src/extras/geometries/EdgesGeometry.js
  21277. /**
  21278. * @author WestLangley / http://github.com/WestLangley
  21279. */
  21280. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  21281. THREE.BufferGeometry.call( this );
  21282. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21283. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  21284. var edge = [ 0, 0 ], hash = {};
  21285. function sortFunction( a, b ) {
  21286. return a - b;
  21287. }
  21288. var keys = [ 'a', 'b', 'c' ];
  21289. var geometry2;
  21290. if ( geometry instanceof THREE.BufferGeometry ) {
  21291. geometry2 = new THREE.Geometry();
  21292. geometry2.fromBufferGeometry( geometry );
  21293. } else {
  21294. geometry2 = geometry.clone();
  21295. }
  21296. geometry2.mergeVertices();
  21297. geometry2.computeFaceNormals();
  21298. var vertices = geometry2.vertices;
  21299. var faces = geometry2.faces;
  21300. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21301. var face = faces[ i ];
  21302. for ( var j = 0; j < 3; j ++ ) {
  21303. edge[ 0 ] = face[ keys[ j ] ];
  21304. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21305. edge.sort( sortFunction );
  21306. var key = edge.toString();
  21307. if ( hash[ key ] === undefined ) {
  21308. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21309. } else {
  21310. hash[ key ].face2 = i;
  21311. }
  21312. }
  21313. }
  21314. var coords = [];
  21315. for ( var key in hash ) {
  21316. var h = hash[ key ];
  21317. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  21318. var vertex = vertices[ h.vert1 ];
  21319. coords.push( vertex.x );
  21320. coords.push( vertex.y );
  21321. coords.push( vertex.z );
  21322. vertex = vertices[ h.vert2 ];
  21323. coords.push( vertex.x );
  21324. coords.push( vertex.y );
  21325. coords.push( vertex.z );
  21326. }
  21327. }
  21328. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  21329. };
  21330. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21331. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  21332. // File:src/extras/geometries/ExtrudeGeometry.js
  21333. /**
  21334. * @author zz85 / http://www.lab4games.net/zz85/blog
  21335. *
  21336. * Creates extruded geometry from a path shape.
  21337. *
  21338. * parameters = {
  21339. *
  21340. * curveSegments: <int>, // number of points on the curves
  21341. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21342. * amount: <int>, // Depth to extrude the shape
  21343. *
  21344. * bevelEnabled: <bool>, // turn on bevel
  21345. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21346. * bevelSize: <float>, // how far from shape outline is bevel
  21347. * bevelSegments: <int>, // number of bevel layers
  21348. *
  21349. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  21350. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  21351. *
  21352. * uvGenerator: <Object> // object that provides UV generator functions
  21353. *
  21354. * }
  21355. **/
  21356. THREE.ExtrudeGeometry = function ( shapes, options ) {
  21357. if ( typeof( shapes ) === "undefined" ) {
  21358. shapes = [];
  21359. return;
  21360. }
  21361. THREE.Geometry.call( this );
  21362. this.type = 'ExtrudeGeometry';
  21363. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21364. this.addShapeList( shapes, options );
  21365. this.computeFaceNormals();
  21366. // can't really use automatic vertex normals
  21367. // as then front and back sides get smoothed too
  21368. // should do separate smoothing just for sides
  21369. //this.computeVertexNormals();
  21370. //console.log( "took", ( Date.now() - startTime ) );
  21371. };
  21372. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21373. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  21374. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21375. var sl = shapes.length;
  21376. for ( var s = 0; s < sl; s ++ ) {
  21377. var shape = shapes[ s ];
  21378. this.addShape( shape, options );
  21379. }
  21380. };
  21381. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  21382. var amount = options.amount !== undefined ? options.amount : 100;
  21383. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  21384. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  21385. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21386. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  21387. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21388. var steps = options.steps !== undefined ? options.steps : 1;
  21389. var extrudePath = options.extrudePath;
  21390. var extrudePts, extrudeByPath = false;
  21391. // Use default WorldUVGenerator if no UV generators are specified.
  21392. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  21393. var splineTube, binormal, normal, position2;
  21394. if ( extrudePath ) {
  21395. extrudePts = extrudePath.getSpacedPoints( steps );
  21396. extrudeByPath = true;
  21397. bevelEnabled = false; // bevels not supported for path extrusion
  21398. // SETUP TNB variables
  21399. // Reuse TNB from TubeGeomtry for now.
  21400. // TODO1 - have a .isClosed in spline?
  21401. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  21402. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21403. binormal = new THREE.Vector3();
  21404. normal = new THREE.Vector3();
  21405. position2 = new THREE.Vector3();
  21406. }
  21407. // Safeguards if bevels are not enabled
  21408. if ( ! bevelEnabled ) {
  21409. bevelSegments = 0;
  21410. bevelThickness = 0;
  21411. bevelSize = 0;
  21412. }
  21413. // Variables initialization
  21414. var ahole, h, hl; // looping of holes
  21415. var scope = this;
  21416. var shapesOffset = this.vertices.length;
  21417. var shapePoints = shape.extractPoints( curveSegments );
  21418. var vertices = shapePoints.shape;
  21419. var holes = shapePoints.holes;
  21420. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21421. if ( reverse ) {
  21422. vertices = vertices.reverse();
  21423. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21424. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21425. ahole = holes[ h ];
  21426. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  21427. holes[ h ] = ahole.reverse();
  21428. }
  21429. }
  21430. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  21431. }
  21432. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21433. /* Vertices */
  21434. var contour = vertices; // vertices has all points but contour has only points of circumference
  21435. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21436. ahole = holes[ h ];
  21437. vertices = vertices.concat( ahole );
  21438. }
  21439. function scalePt2 ( pt, vec, size ) {
  21440. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21441. return vec.clone().multiplyScalar( size ).add( pt );
  21442. }
  21443. var b, bs, t, z,
  21444. vert, vlen = vertices.length,
  21445. face, flen = faces.length;
  21446. // Find directions for point movement
  21447. function getBevelVec( inPt, inPrev, inNext ) {
  21448. // computes for inPt the corresponding point inPt' on a new contour
  21449. // shifted by 1 unit (length of normalized vector) to the left
  21450. // if we walk along contour clockwise, this new contour is outside the old one
  21451. //
  21452. // inPt' is the intersection of the two lines parallel to the two
  21453. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21454. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  21455. // good reading for geometry algorithms (here: line-line intersection)
  21456. // http://geomalgorithms.com/a05-_intersect-1.html
  21457. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  21458. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  21459. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21460. // check for collinear edges
  21461. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21462. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21463. // not collinear
  21464. // length of vectors for normalizing
  21465. var v_prev_len = Math.sqrt( v_prev_lensq );
  21466. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21467. // shift adjacent points by unit vectors to the left
  21468. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21469. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21470. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21471. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21472. // scaling factor for v_prev to intersection point
  21473. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21474. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21475. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21476. // vector from inPt to intersection point
  21477. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21478. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21479. // Don't normalize!, otherwise sharp corners become ugly
  21480. // but prevent crazy spikes
  21481. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21482. if ( v_trans_lensq <= 2 ) {
  21483. return new THREE.Vector2( v_trans_x, v_trans_y );
  21484. } else {
  21485. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21486. }
  21487. } else {
  21488. // handle special case of collinear edges
  21489. var direction_eq = false; // assumes: opposite
  21490. if ( v_prev_x > Number.EPSILON ) {
  21491. if ( v_next_x > Number.EPSILON ) {
  21492. direction_eq = true;
  21493. }
  21494. } else {
  21495. if ( v_prev_x < - Number.EPSILON ) {
  21496. if ( v_next_x < - Number.EPSILON ) {
  21497. direction_eq = true;
  21498. }
  21499. } else {
  21500. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21501. direction_eq = true;
  21502. }
  21503. }
  21504. }
  21505. if ( direction_eq ) {
  21506. // console.log("Warning: lines are a straight sequence");
  21507. v_trans_x = - v_prev_y;
  21508. v_trans_y = v_prev_x;
  21509. shrink_by = Math.sqrt( v_prev_lensq );
  21510. } else {
  21511. // console.log("Warning: lines are a straight spike");
  21512. v_trans_x = v_prev_x;
  21513. v_trans_y = v_prev_y;
  21514. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21515. }
  21516. }
  21517. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21518. }
  21519. var contourMovements = [];
  21520. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21521. if ( j === il ) j = 0;
  21522. if ( k === il ) k = 0;
  21523. // (j)---(i)---(k)
  21524. // console.log('i,j,k', i, j , k)
  21525. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21526. }
  21527. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  21528. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21529. ahole = holes[ h ];
  21530. oneHoleMovements = [];
  21531. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21532. if ( j === il ) j = 0;
  21533. if ( k === il ) k = 0;
  21534. // (j)---(i)---(k)
  21535. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21536. }
  21537. holesMovements.push( oneHoleMovements );
  21538. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21539. }
  21540. // Loop bevelSegments, 1 for the front, 1 for the back
  21541. for ( b = 0; b < bevelSegments; b ++ ) {
  21542. //for ( b = bevelSegments; b > 0; b -- ) {
  21543. t = b / bevelSegments;
  21544. z = bevelThickness * ( 1 - t );
  21545. //z = bevelThickness * t;
  21546. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  21547. //bs = bevelSize * t; // linear
  21548. // contract shape
  21549. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21550. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21551. v( vert.x, vert.y, - z );
  21552. }
  21553. // expand holes
  21554. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21555. ahole = holes[ h ];
  21556. oneHoleMovements = holesMovements[ h ];
  21557. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21558. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21559. v( vert.x, vert.y, - z );
  21560. }
  21561. }
  21562. }
  21563. bs = bevelSize;
  21564. // Back facing vertices
  21565. for ( i = 0; i < vlen; i ++ ) {
  21566. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21567. if ( ! extrudeByPath ) {
  21568. v( vert.x, vert.y, 0 );
  21569. } else {
  21570. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21571. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21572. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21573. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21574. v( position2.x, position2.y, position2.z );
  21575. }
  21576. }
  21577. // Add stepped vertices...
  21578. // Including front facing vertices
  21579. var s;
  21580. for ( s = 1; s <= steps; s ++ ) {
  21581. for ( i = 0; i < vlen; i ++ ) {
  21582. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21583. if ( ! extrudeByPath ) {
  21584. v( vert.x, vert.y, amount / steps * s );
  21585. } else {
  21586. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21587. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21588. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21589. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21590. v( position2.x, position2.y, position2.z );
  21591. }
  21592. }
  21593. }
  21594. // Add bevel segments planes
  21595. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21596. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21597. t = b / bevelSegments;
  21598. z = bevelThickness * ( 1 - t );
  21599. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  21600. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  21601. // contract shape
  21602. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21603. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21604. v( vert.x, vert.y, amount + z );
  21605. }
  21606. // expand holes
  21607. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21608. ahole = holes[ h ];
  21609. oneHoleMovements = holesMovements[ h ];
  21610. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21611. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21612. if ( ! extrudeByPath ) {
  21613. v( vert.x, vert.y, amount + z );
  21614. } else {
  21615. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21616. }
  21617. }
  21618. }
  21619. }
  21620. /* Faces */
  21621. // Top and bottom faces
  21622. buildLidFaces();
  21623. // Sides faces
  21624. buildSideFaces();
  21625. ///// Internal functions
  21626. function buildLidFaces() {
  21627. if ( bevelEnabled ) {
  21628. var layer = 0; // steps + 1
  21629. var offset = vlen * layer;
  21630. // Bottom faces
  21631. for ( i = 0; i < flen; i ++ ) {
  21632. face = faces[ i ];
  21633. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21634. }
  21635. layer = steps + bevelSegments * 2;
  21636. offset = vlen * layer;
  21637. // Top faces
  21638. for ( i = 0; i < flen; i ++ ) {
  21639. face = faces[ i ];
  21640. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21641. }
  21642. } else {
  21643. // Bottom faces
  21644. for ( i = 0; i < flen; i ++ ) {
  21645. face = faces[ i ];
  21646. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21647. }
  21648. // Top faces
  21649. for ( i = 0; i < flen; i ++ ) {
  21650. face = faces[ i ];
  21651. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21652. }
  21653. }
  21654. }
  21655. // Create faces for the z-sides of the shape
  21656. function buildSideFaces() {
  21657. var layeroffset = 0;
  21658. sidewalls( contour, layeroffset );
  21659. layeroffset += contour.length;
  21660. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21661. ahole = holes[ h ];
  21662. sidewalls( ahole, layeroffset );
  21663. //, true
  21664. layeroffset += ahole.length;
  21665. }
  21666. }
  21667. function sidewalls( contour, layeroffset ) {
  21668. var j, k;
  21669. i = contour.length;
  21670. while ( -- i >= 0 ) {
  21671. j = i;
  21672. k = i - 1;
  21673. if ( k < 0 ) k = contour.length - 1;
  21674. //console.log('b', i,j, i-1, k,vertices.length);
  21675. var s = 0, sl = steps + bevelSegments * 2;
  21676. for ( s = 0; s < sl; s ++ ) {
  21677. var slen1 = vlen * s;
  21678. var slen2 = vlen * ( s + 1 );
  21679. var a = layeroffset + j + slen1,
  21680. b = layeroffset + k + slen1,
  21681. c = layeroffset + k + slen2,
  21682. d = layeroffset + j + slen2;
  21683. f4( a, b, c, d, contour, s, sl, j, k );
  21684. }
  21685. }
  21686. }
  21687. function v( x, y, z ) {
  21688. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  21689. }
  21690. function f3( a, b, c ) {
  21691. a += shapesOffset;
  21692. b += shapesOffset;
  21693. c += shapesOffset;
  21694. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  21695. var uvs = uvgen.generateTopUV( scope, a, b, c );
  21696. scope.faceVertexUvs[ 0 ].push( uvs );
  21697. }
  21698. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  21699. a += shapesOffset;
  21700. b += shapesOffset;
  21701. c += shapesOffset;
  21702. d += shapesOffset;
  21703. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  21704. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  21705. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  21706. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  21707. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  21708. }
  21709. };
  21710. THREE.ExtrudeGeometry.WorldUVGenerator = {
  21711. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  21712. var vertices = geometry.vertices;
  21713. var a = vertices[ indexA ];
  21714. var b = vertices[ indexB ];
  21715. var c = vertices[ indexC ];
  21716. return [
  21717. new THREE.Vector2( a.x, a.y ),
  21718. new THREE.Vector2( b.x, b.y ),
  21719. new THREE.Vector2( c.x, c.y )
  21720. ];
  21721. },
  21722. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  21723. var vertices = geometry.vertices;
  21724. var a = vertices[ indexA ];
  21725. var b = vertices[ indexB ];
  21726. var c = vertices[ indexC ];
  21727. var d = vertices[ indexD ];
  21728. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  21729. return [
  21730. new THREE.Vector2( a.x, 1 - a.z ),
  21731. new THREE.Vector2( b.x, 1 - b.z ),
  21732. new THREE.Vector2( c.x, 1 - c.z ),
  21733. new THREE.Vector2( d.x, 1 - d.z )
  21734. ];
  21735. } else {
  21736. return [
  21737. new THREE.Vector2( a.y, 1 - a.z ),
  21738. new THREE.Vector2( b.y, 1 - b.z ),
  21739. new THREE.Vector2( c.y, 1 - c.z ),
  21740. new THREE.Vector2( d.y, 1 - d.z )
  21741. ];
  21742. }
  21743. }
  21744. };
  21745. // File:src/extras/geometries/ShapeGeometry.js
  21746. /**
  21747. * @author jonobr1 / http://jonobr1.com
  21748. *
  21749. * Creates a one-sided polygonal geometry from a path shape. Similar to
  21750. * ExtrudeGeometry.
  21751. *
  21752. * parameters = {
  21753. *
  21754. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  21755. *
  21756. * material: <int> // material index for front and back faces
  21757. * uvGenerator: <Object> // object that provides UV generator functions
  21758. *
  21759. * }
  21760. **/
  21761. THREE.ShapeGeometry = function ( shapes, options ) {
  21762. THREE.Geometry.call( this );
  21763. this.type = 'ShapeGeometry';
  21764. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  21765. this.addShapeList( shapes, options );
  21766. this.computeFaceNormals();
  21767. };
  21768. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21769. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  21770. /**
  21771. * Add an array of shapes to THREE.ShapeGeometry.
  21772. */
  21773. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21774. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21775. this.addShape( shapes[ i ], options );
  21776. }
  21777. return this;
  21778. };
  21779. /**
  21780. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  21781. */
  21782. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  21783. if ( options === undefined ) options = {};
  21784. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21785. var material = options.material;
  21786. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  21787. //
  21788. var i, l, hole;
  21789. var shapesOffset = this.vertices.length;
  21790. var shapePoints = shape.extractPoints( curveSegments );
  21791. var vertices = shapePoints.shape;
  21792. var holes = shapePoints.holes;
  21793. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21794. if ( reverse ) {
  21795. vertices = vertices.reverse();
  21796. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  21797. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21798. hole = holes[ i ];
  21799. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  21800. holes[ i ] = hole.reverse();
  21801. }
  21802. }
  21803. reverse = false;
  21804. }
  21805. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21806. // Vertices
  21807. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21808. hole = holes[ i ];
  21809. vertices = vertices.concat( hole );
  21810. }
  21811. //
  21812. var vert, vlen = vertices.length;
  21813. var face, flen = faces.length;
  21814. for ( i = 0; i < vlen; i ++ ) {
  21815. vert = vertices[ i ];
  21816. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  21817. }
  21818. for ( i = 0; i < flen; i ++ ) {
  21819. face = faces[ i ];
  21820. var a = face[ 0 ] + shapesOffset;
  21821. var b = face[ 1 ] + shapesOffset;
  21822. var c = face[ 2 ] + shapesOffset;
  21823. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  21824. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  21825. }
  21826. };
  21827. // File:src/extras/geometries/LatheGeometry.js
  21828. /**
  21829. * @author astrodud / http://astrodud.isgreat.org/
  21830. * @author zz85 / https://github.com/zz85
  21831. * @author bhouston / http://clara.io
  21832. */
  21833. // points - to create a closed torus, one must use a set of points
  21834. // like so: [ a, b, c, d, a ], see first is the same as last.
  21835. // segments - the number of circumference segments to create
  21836. // phiStart - the starting radian
  21837. // phiLength - the radian (0 to 2*PI) range of the lathed section
  21838. // 2*pi is a closed lathe, less than 2PI is a portion.
  21839. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  21840. THREE.Geometry.call( this );
  21841. this.type = 'LatheGeometry';
  21842. this.parameters = {
  21843. points: points,
  21844. segments: segments,
  21845. phiStart: phiStart,
  21846. phiLength: phiLength
  21847. };
  21848. segments = segments || 12;
  21849. phiStart = phiStart || 0;
  21850. phiLength = phiLength || 2 * Math.PI;
  21851. var inversePointLength = 1.0 / ( points.length - 1 );
  21852. var inverseSegments = 1.0 / segments;
  21853. for ( var i = 0, il = segments; i <= il; i ++ ) {
  21854. var phi = phiStart + i * inverseSegments * phiLength;
  21855. var c = Math.cos( phi ),
  21856. s = Math.sin( phi );
  21857. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  21858. var pt = points[ j ];
  21859. var vertex = new THREE.Vector3();
  21860. vertex.x = c * pt.x - s * pt.y;
  21861. vertex.y = s * pt.x + c * pt.y;
  21862. vertex.z = pt.z;
  21863. this.vertices.push( vertex );
  21864. }
  21865. }
  21866. var np = points.length;
  21867. for ( var i = 0, il = segments; i < il; i ++ ) {
  21868. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  21869. var base = j + np * i;
  21870. var a = base;
  21871. var b = base + np;
  21872. var c = base + 1 + np;
  21873. var d = base + 1;
  21874. var u0 = i * inverseSegments;
  21875. var v0 = j * inversePointLength;
  21876. var u1 = u0 + inverseSegments;
  21877. var v1 = v0 + inversePointLength;
  21878. this.faces.push( new THREE.Face3( a, b, d ) );
  21879. this.faceVertexUvs[ 0 ].push( [
  21880. new THREE.Vector2( u0, v0 ),
  21881. new THREE.Vector2( u1, v0 ),
  21882. new THREE.Vector2( u0, v1 )
  21883. ] );
  21884. this.faces.push( new THREE.Face3( b, c, d ) );
  21885. this.faceVertexUvs[ 0 ].push( [
  21886. new THREE.Vector2( u1, v0 ),
  21887. new THREE.Vector2( u1, v1 ),
  21888. new THREE.Vector2( u0, v1 )
  21889. ] );
  21890. }
  21891. }
  21892. this.mergeVertices();
  21893. this.computeFaceNormals();
  21894. this.computeVertexNormals();
  21895. };
  21896. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21897. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  21898. // File:src/extras/geometries/PlaneGeometry.js
  21899. /**
  21900. * @author mrdoob / http://mrdoob.com/
  21901. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  21902. */
  21903. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  21904. THREE.Geometry.call( this );
  21905. this.type = 'PlaneGeometry';
  21906. this.parameters = {
  21907. width: width,
  21908. height: height,
  21909. widthSegments: widthSegments,
  21910. heightSegments: heightSegments
  21911. };
  21912. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  21913. };
  21914. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21915. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  21916. // File:src/extras/geometries/PlaneBufferGeometry.js
  21917. /**
  21918. * @author mrdoob / http://mrdoob.com/
  21919. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  21920. */
  21921. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  21922. THREE.BufferGeometry.call( this );
  21923. this.type = 'PlaneBufferGeometry';
  21924. this.parameters = {
  21925. width: width,
  21926. height: height,
  21927. widthSegments: widthSegments,
  21928. heightSegments: heightSegments
  21929. };
  21930. var width_half = width / 2;
  21931. var height_half = height / 2;
  21932. var gridX = Math.floor( widthSegments ) || 1;
  21933. var gridY = Math.floor( heightSegments ) || 1;
  21934. var gridX1 = gridX + 1;
  21935. var gridY1 = gridY + 1;
  21936. var segment_width = width / gridX;
  21937. var segment_height = height / gridY;
  21938. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  21939. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  21940. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  21941. var offset = 0;
  21942. var offset2 = 0;
  21943. for ( var iy = 0; iy < gridY1; iy ++ ) {
  21944. var y = iy * segment_height - height_half;
  21945. for ( var ix = 0; ix < gridX1; ix ++ ) {
  21946. var x = ix * segment_width - width_half;
  21947. vertices[ offset ] = x;
  21948. vertices[ offset + 1 ] = - y;
  21949. normals[ offset + 2 ] = 1;
  21950. uvs[ offset2 ] = ix / gridX;
  21951. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  21952. offset += 3;
  21953. offset2 += 2;
  21954. }
  21955. }
  21956. offset = 0;
  21957. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  21958. for ( var iy = 0; iy < gridY; iy ++ ) {
  21959. for ( var ix = 0; ix < gridX; ix ++ ) {
  21960. var a = ix + gridX1 * iy;
  21961. var b = ix + gridX1 * ( iy + 1 );
  21962. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21963. var d = ( ix + 1 ) + gridX1 * iy;
  21964. indices[ offset ] = a;
  21965. indices[ offset + 1 ] = b;
  21966. indices[ offset + 2 ] = d;
  21967. indices[ offset + 3 ] = b;
  21968. indices[ offset + 4 ] = c;
  21969. indices[ offset + 5 ] = d;
  21970. offset += 6;
  21971. }
  21972. }
  21973. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  21974. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  21975. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21976. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21977. };
  21978. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21979. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  21980. // File:src/extras/geometries/RingGeometry.js
  21981. /**
  21982. * @author Kaleb Murphy
  21983. */
  21984. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21985. THREE.Geometry.call( this );
  21986. this.type = 'RingGeometry';
  21987. this.parameters = {
  21988. innerRadius: innerRadius,
  21989. outerRadius: outerRadius,
  21990. thetaSegments: thetaSegments,
  21991. phiSegments: phiSegments,
  21992. thetaStart: thetaStart,
  21993. thetaLength: thetaLength
  21994. };
  21995. innerRadius = innerRadius || 0;
  21996. outerRadius = outerRadius || 50;
  21997. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21998. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21999. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22000. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  22001. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22002. for ( i = 0; i < phiSegments + 1; i ++ ) {
  22003. // concentric circles inside ring
  22004. for ( o = 0; o < thetaSegments + 1; o ++ ) {
  22005. // number of segments per circle
  22006. var vertex = new THREE.Vector3();
  22007. var segment = thetaStart + o / thetaSegments * thetaLength;
  22008. vertex.x = radius * Math.cos( segment );
  22009. vertex.y = radius * Math.sin( segment );
  22010. this.vertices.push( vertex );
  22011. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  22012. }
  22013. radius += radiusStep;
  22014. }
  22015. var n = new THREE.Vector3( 0, 0, 1 );
  22016. for ( i = 0; i < phiSegments; i ++ ) {
  22017. // concentric circles inside ring
  22018. var thetaSegment = i * ( thetaSegments + 1 );
  22019. for ( o = 0; o < thetaSegments ; o ++ ) {
  22020. // number of segments per circle
  22021. var segment = o + thetaSegment;
  22022. var v1 = segment;
  22023. var v2 = segment + thetaSegments + 1;
  22024. var v3 = segment + thetaSegments + 2;
  22025. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22026. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22027. v1 = segment;
  22028. v2 = segment + thetaSegments + 2;
  22029. v3 = segment + 1;
  22030. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22031. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22032. }
  22033. }
  22034. this.computeFaceNormals();
  22035. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22036. };
  22037. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22038. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  22039. // File:src/extras/geometries/SphereGeometry.js
  22040. /**
  22041. * @author mrdoob / http://mrdoob.com/
  22042. */
  22043. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22044. THREE.Geometry.call( this );
  22045. this.type = 'SphereGeometry';
  22046. this.parameters = {
  22047. radius: radius,
  22048. widthSegments: widthSegments,
  22049. heightSegments: heightSegments,
  22050. phiStart: phiStart,
  22051. phiLength: phiLength,
  22052. thetaStart: thetaStart,
  22053. thetaLength: thetaLength
  22054. };
  22055. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22056. };
  22057. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22058. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  22059. // File:src/extras/geometries/SphereBufferGeometry.js
  22060. /**
  22061. * @author benaadams / https://twitter.com/ben_a_adams
  22062. * based on THREE.SphereGeometry
  22063. */
  22064. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22065. THREE.BufferGeometry.call( this );
  22066. this.type = 'SphereBufferGeometry';
  22067. this.parameters = {
  22068. radius: radius,
  22069. widthSegments: widthSegments,
  22070. heightSegments: heightSegments,
  22071. phiStart: phiStart,
  22072. phiLength: phiLength,
  22073. thetaStart: thetaStart,
  22074. thetaLength: thetaLength
  22075. };
  22076. radius = radius || 50;
  22077. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22078. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22079. phiStart = phiStart !== undefined ? phiStart : 0;
  22080. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22081. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22082. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22083. var thetaEnd = thetaStart + thetaLength;
  22084. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22085. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22086. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22087. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22088. var index = 0, vertices = [], normal = new THREE.Vector3();
  22089. for ( var y = 0; y <= heightSegments; y ++ ) {
  22090. var verticesRow = [];
  22091. var v = y / heightSegments;
  22092. for ( var x = 0; x <= widthSegments; x ++ ) {
  22093. var u = x / widthSegments;
  22094. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22095. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22096. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22097. normal.set( px, py, pz ).normalize();
  22098. positions.setXYZ( index, px, py, pz );
  22099. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22100. uvs.setXY( index, u, 1 - v );
  22101. verticesRow.push( index );
  22102. index ++;
  22103. }
  22104. vertices.push( verticesRow );
  22105. }
  22106. var indices = [];
  22107. for ( var y = 0; y < heightSegments; y ++ ) {
  22108. for ( var x = 0; x < widthSegments; x ++ ) {
  22109. var v1 = vertices[ y ][ x + 1 ];
  22110. var v2 = vertices[ y ][ x ];
  22111. var v3 = vertices[ y + 1 ][ x ];
  22112. var v4 = vertices[ y + 1 ][ x + 1 ];
  22113. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22114. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22115. }
  22116. }
  22117. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  22118. this.addAttribute( 'position', positions );
  22119. this.addAttribute( 'normal', normals );
  22120. this.addAttribute( 'uv', uvs );
  22121. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22122. };
  22123. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22124. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  22125. // File:src/extras/geometries/TorusGeometry.js
  22126. /**
  22127. * @author oosmoxiecode
  22128. * @author mrdoob / http://mrdoob.com/
  22129. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  22130. */
  22131. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22132. THREE.Geometry.call( this );
  22133. this.type = 'TorusGeometry';
  22134. this.parameters = {
  22135. radius: radius,
  22136. tube: tube,
  22137. radialSegments: radialSegments,
  22138. tubularSegments: tubularSegments,
  22139. arc: arc
  22140. };
  22141. radius = radius || 100;
  22142. tube = tube || 40;
  22143. radialSegments = radialSegments || 8;
  22144. tubularSegments = tubularSegments || 6;
  22145. arc = arc || Math.PI * 2;
  22146. var center = new THREE.Vector3(), uvs = [], normals = [];
  22147. for ( var j = 0; j <= radialSegments; j ++ ) {
  22148. for ( var i = 0; i <= tubularSegments; i ++ ) {
  22149. var u = i / tubularSegments * arc;
  22150. var v = j / radialSegments * Math.PI * 2;
  22151. center.x = radius * Math.cos( u );
  22152. center.y = radius * Math.sin( u );
  22153. var vertex = new THREE.Vector3();
  22154. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22155. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22156. vertex.z = tube * Math.sin( v );
  22157. this.vertices.push( vertex );
  22158. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  22159. normals.push( vertex.clone().sub( center ).normalize() );
  22160. }
  22161. }
  22162. for ( var j = 1; j <= radialSegments; j ++ ) {
  22163. for ( var i = 1; i <= tubularSegments; i ++ ) {
  22164. var a = ( tubularSegments + 1 ) * j + i - 1;
  22165. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22166. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22167. var d = ( tubularSegments + 1 ) * j + i;
  22168. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  22169. this.faces.push( face );
  22170. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  22171. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  22172. this.faces.push( face );
  22173. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  22174. }
  22175. }
  22176. this.computeFaceNormals();
  22177. };
  22178. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22179. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  22180. // File:src/extras/geometries/TorusKnotGeometry.js
  22181. /**
  22182. * @author oosmoxiecode
  22183. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22184. */
  22185. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  22186. THREE.Geometry.call( this );
  22187. this.type = 'TorusKnotGeometry';
  22188. this.parameters = {
  22189. radius: radius,
  22190. tube: tube,
  22191. radialSegments: radialSegments,
  22192. tubularSegments: tubularSegments,
  22193. p: p,
  22194. q: q,
  22195. heightScale: heightScale
  22196. };
  22197. radius = radius || 100;
  22198. tube = tube || 40;
  22199. radialSegments = radialSegments || 64;
  22200. tubularSegments = tubularSegments || 8;
  22201. p = p || 2;
  22202. q = q || 3;
  22203. heightScale = heightScale || 1;
  22204. var grid = new Array( radialSegments );
  22205. var tang = new THREE.Vector3();
  22206. var n = new THREE.Vector3();
  22207. var bitan = new THREE.Vector3();
  22208. for ( var i = 0; i < radialSegments; ++ i ) {
  22209. grid[ i ] = new Array( tubularSegments );
  22210. var u = i / radialSegments * 2 * p * Math.PI;
  22211. var p1 = getPos( u, q, p, radius, heightScale );
  22212. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  22213. tang.subVectors( p2, p1 );
  22214. n.addVectors( p2, p1 );
  22215. bitan.crossVectors( tang, n );
  22216. n.crossVectors( bitan, tang );
  22217. bitan.normalize();
  22218. n.normalize();
  22219. for ( var j = 0; j < tubularSegments; ++ j ) {
  22220. var v = j / tubularSegments * 2 * Math.PI;
  22221. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22222. var cy = tube * Math.sin( v );
  22223. var pos = new THREE.Vector3();
  22224. pos.x = p1.x + cx * n.x + cy * bitan.x;
  22225. pos.y = p1.y + cx * n.y + cy * bitan.y;
  22226. pos.z = p1.z + cx * n.z + cy * bitan.z;
  22227. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  22228. }
  22229. }
  22230. for ( var i = 0; i < radialSegments; ++ i ) {
  22231. for ( var j = 0; j < tubularSegments; ++ j ) {
  22232. var ip = ( i + 1 ) % radialSegments;
  22233. var jp = ( j + 1 ) % tubularSegments;
  22234. var a = grid[ i ][ j ];
  22235. var b = grid[ ip ][ j ];
  22236. var c = grid[ ip ][ jp ];
  22237. var d = grid[ i ][ jp ];
  22238. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  22239. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  22240. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  22241. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  22242. this.faces.push( new THREE.Face3( a, b, d ) );
  22243. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22244. this.faces.push( new THREE.Face3( b, c, d ) );
  22245. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22246. }
  22247. }
  22248. this.computeFaceNormals();
  22249. this.computeVertexNormals();
  22250. function getPos( u, in_q, in_p, radius, heightScale ) {
  22251. var cu = Math.cos( u );
  22252. var su = Math.sin( u );
  22253. var quOverP = in_q / in_p * u;
  22254. var cs = Math.cos( quOverP );
  22255. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  22256. var ty = radius * ( 2 + cs ) * su * 0.5;
  22257. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  22258. return new THREE.Vector3( tx, ty, tz );
  22259. }
  22260. };
  22261. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22262. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  22263. // File:src/extras/geometries/TubeGeometry.js
  22264. /**
  22265. * @author WestLangley / https://github.com/WestLangley
  22266. * @author zz85 / https://github.com/zz85
  22267. * @author miningold / https://github.com/miningold
  22268. * @author jonobr1 / https://github.com/jonobr1
  22269. *
  22270. * Modified from the TorusKnotGeometry by @oosmoxiecode
  22271. *
  22272. * Creates a tube which extrudes along a 3d spline
  22273. *
  22274. * Uses parallel transport frames as described in
  22275. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22276. */
  22277. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  22278. THREE.Geometry.call( this );
  22279. this.type = 'TubeGeometry';
  22280. this.parameters = {
  22281. path: path,
  22282. segments: segments,
  22283. radius: radius,
  22284. radialSegments: radialSegments,
  22285. closed: closed,
  22286. taper: taper
  22287. };
  22288. segments = segments || 64;
  22289. radius = radius || 1;
  22290. radialSegments = radialSegments || 8;
  22291. closed = closed || false;
  22292. taper = taper || THREE.TubeGeometry.NoTaper;
  22293. var grid = [];
  22294. var scope = this,
  22295. tangent,
  22296. normal,
  22297. binormal,
  22298. numpoints = segments + 1,
  22299. u, v, r,
  22300. cx, cy,
  22301. pos, pos2 = new THREE.Vector3(),
  22302. i, j,
  22303. ip, jp,
  22304. a, b, c, d,
  22305. uva, uvb, uvc, uvd;
  22306. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  22307. tangents = frames.tangents,
  22308. normals = frames.normals,
  22309. binormals = frames.binormals;
  22310. // proxy internals
  22311. this.tangents = tangents;
  22312. this.normals = normals;
  22313. this.binormals = binormals;
  22314. function vert( x, y, z ) {
  22315. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  22316. }
  22317. // construct the grid
  22318. for ( i = 0; i < numpoints; i ++ ) {
  22319. grid[ i ] = [];
  22320. u = i / ( numpoints - 1 );
  22321. pos = path.getPointAt( u );
  22322. tangent = tangents[ i ];
  22323. normal = normals[ i ];
  22324. binormal = binormals[ i ];
  22325. r = radius * taper( u );
  22326. for ( j = 0; j < radialSegments; j ++ ) {
  22327. v = j / radialSegments * 2 * Math.PI;
  22328. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22329. cy = r * Math.sin( v );
  22330. pos2.copy( pos );
  22331. pos2.x += cx * normal.x + cy * binormal.x;
  22332. pos2.y += cx * normal.y + cy * binormal.y;
  22333. pos2.z += cx * normal.z + cy * binormal.z;
  22334. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  22335. }
  22336. }
  22337. // construct the mesh
  22338. for ( i = 0; i < segments; i ++ ) {
  22339. for ( j = 0; j < radialSegments; j ++ ) {
  22340. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  22341. jp = ( j + 1 ) % radialSegments;
  22342. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  22343. b = grid[ ip ][ j ];
  22344. c = grid[ ip ][ jp ];
  22345. d = grid[ i ][ jp ];
  22346. uva = new THREE.Vector2( i / segments, j / radialSegments );
  22347. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  22348. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  22349. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  22350. this.faces.push( new THREE.Face3( a, b, d ) );
  22351. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22352. this.faces.push( new THREE.Face3( b, c, d ) );
  22353. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22354. }
  22355. }
  22356. this.computeFaceNormals();
  22357. this.computeVertexNormals();
  22358. };
  22359. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22360. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  22361. THREE.TubeGeometry.NoTaper = function ( u ) {
  22362. return 1;
  22363. };
  22364. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  22365. return Math.sin( Math.PI * u );
  22366. };
  22367. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  22368. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  22369. var normal = new THREE.Vector3(),
  22370. tangents = [],
  22371. normals = [],
  22372. binormals = [],
  22373. vec = new THREE.Vector3(),
  22374. mat = new THREE.Matrix4(),
  22375. numpoints = segments + 1,
  22376. theta,
  22377. smallest,
  22378. tx, ty, tz,
  22379. i, u;
  22380. // expose internals
  22381. this.tangents = tangents;
  22382. this.normals = normals;
  22383. this.binormals = binormals;
  22384. // compute the tangent vectors for each segment on the path
  22385. for ( i = 0; i < numpoints; i ++ ) {
  22386. u = i / ( numpoints - 1 );
  22387. tangents[ i ] = path.getTangentAt( u );
  22388. tangents[ i ].normalize();
  22389. }
  22390. initialNormal3();
  22391. /*
  22392. function initialNormal1(lastBinormal) {
  22393. // fixed start binormal. Has dangers of 0 vectors
  22394. normals[ 0 ] = new THREE.Vector3();
  22395. binormals[ 0 ] = new THREE.Vector3();
  22396. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  22397. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  22398. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22399. }
  22400. function initialNormal2() {
  22401. // This uses the Frenet-Serret formula for deriving binormal
  22402. var t2 = path.getTangentAt( epsilon );
  22403. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  22404. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  22405. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  22406. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22407. }
  22408. */
  22409. function initialNormal3() {
  22410. // select an initial normal vector perpendicular to the first tangent vector,
  22411. // and in the direction of the smallest tangent xyz component
  22412. normals[ 0 ] = new THREE.Vector3();
  22413. binormals[ 0 ] = new THREE.Vector3();
  22414. smallest = Number.MAX_VALUE;
  22415. tx = Math.abs( tangents[ 0 ].x );
  22416. ty = Math.abs( tangents[ 0 ].y );
  22417. tz = Math.abs( tangents[ 0 ].z );
  22418. if ( tx <= smallest ) {
  22419. smallest = tx;
  22420. normal.set( 1, 0, 0 );
  22421. }
  22422. if ( ty <= smallest ) {
  22423. smallest = ty;
  22424. normal.set( 0, 1, 0 );
  22425. }
  22426. if ( tz <= smallest ) {
  22427. normal.set( 0, 0, 1 );
  22428. }
  22429. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22430. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22431. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22432. }
  22433. // compute the slowly-varying normal and binormal vectors for each segment on the path
  22434. for ( i = 1; i < numpoints; i ++ ) {
  22435. normals[ i ] = normals[ i - 1 ].clone();
  22436. binormals[ i ] = binormals[ i - 1 ].clone();
  22437. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22438. if ( vec.length() > Number.EPSILON ) {
  22439. vec.normalize();
  22440. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22441. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22442. }
  22443. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22444. }
  22445. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22446. if ( closed ) {
  22447. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  22448. theta /= ( numpoints - 1 );
  22449. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  22450. theta = - theta;
  22451. }
  22452. for ( i = 1; i < numpoints; i ++ ) {
  22453. // twist a little...
  22454. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22455. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22456. }
  22457. }
  22458. };
  22459. // File:src/extras/geometries/PolyhedronGeometry.js
  22460. /**
  22461. * @author clockworkgeek / https://github.com/clockworkgeek
  22462. * @author timothypratley / https://github.com/timothypratley
  22463. * @author WestLangley / http://github.com/WestLangley
  22464. */
  22465. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  22466. THREE.Geometry.call( this );
  22467. this.type = 'PolyhedronGeometry';
  22468. this.parameters = {
  22469. vertices: vertices,
  22470. indices: indices,
  22471. radius: radius,
  22472. detail: detail
  22473. };
  22474. radius = radius || 1;
  22475. detail = detail || 0;
  22476. var that = this;
  22477. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  22478. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  22479. }
  22480. var p = this.vertices;
  22481. var faces = [];
  22482. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  22483. var v1 = p[ indices[ i ] ];
  22484. var v2 = p[ indices[ i + 1 ] ];
  22485. var v3 = p[ indices[ i + 2 ] ];
  22486. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  22487. }
  22488. var centroid = new THREE.Vector3();
  22489. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22490. subdivide( faces[ i ], detail );
  22491. }
  22492. // Handle case when face straddles the seam
  22493. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  22494. var uvs = this.faceVertexUvs[ 0 ][ i ];
  22495. var x0 = uvs[ 0 ].x;
  22496. var x1 = uvs[ 1 ].x;
  22497. var x2 = uvs[ 2 ].x;
  22498. var max = Math.max( x0, x1, x2 );
  22499. var min = Math.min( x0, x1, x2 );
  22500. if ( max > 0.9 && min < 0.1 ) {
  22501. // 0.9 is somewhat arbitrary
  22502. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  22503. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  22504. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  22505. }
  22506. }
  22507. // Apply radius
  22508. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  22509. this.vertices[ i ].multiplyScalar( radius );
  22510. }
  22511. // Merge vertices
  22512. this.mergeVertices();
  22513. this.computeFaceNormals();
  22514. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22515. // Project vector onto sphere's surface
  22516. function prepare( vector ) {
  22517. var vertex = vector.normalize().clone();
  22518. vertex.index = that.vertices.push( vertex ) - 1;
  22519. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  22520. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  22521. var v = inclination( vector ) / Math.PI + 0.5;
  22522. vertex.uv = new THREE.Vector2( u, 1 - v );
  22523. return vertex;
  22524. }
  22525. // Approximate a curved face with recursively sub-divided triangles.
  22526. function make( v1, v2, v3, materialIndex ) {
  22527. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  22528. that.faces.push( face );
  22529. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  22530. var azi = azimuth( centroid );
  22531. that.faceVertexUvs[ 0 ].push( [
  22532. correctUV( v1.uv, v1, azi ),
  22533. correctUV( v2.uv, v2, azi ),
  22534. correctUV( v3.uv, v3, azi )
  22535. ] );
  22536. }
  22537. // Analytically subdivide a face to the required detail level.
  22538. function subdivide( face, detail ) {
  22539. var cols = Math.pow( 2, detail );
  22540. var a = prepare( that.vertices[ face.a ] );
  22541. var b = prepare( that.vertices[ face.b ] );
  22542. var c = prepare( that.vertices[ face.c ] );
  22543. var v = [];
  22544. var materialIndex = face.materialIndex;
  22545. // Construct all of the vertices for this subdivision.
  22546. for ( var i = 0 ; i <= cols; i ++ ) {
  22547. v[ i ] = [];
  22548. var aj = prepare( a.clone().lerp( c, i / cols ) );
  22549. var bj = prepare( b.clone().lerp( c, i / cols ) );
  22550. var rows = cols - i;
  22551. for ( var j = 0; j <= rows; j ++ ) {
  22552. if ( j === 0 && i === cols ) {
  22553. v[ i ][ j ] = aj;
  22554. } else {
  22555. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  22556. }
  22557. }
  22558. }
  22559. // Construct all of the faces.
  22560. for ( var i = 0; i < cols ; i ++ ) {
  22561. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22562. var k = Math.floor( j / 2 );
  22563. if ( j % 2 === 0 ) {
  22564. make(
  22565. v[ i ][ k + 1 ],
  22566. v[ i + 1 ][ k ],
  22567. v[ i ][ k ],
  22568. materialIndex
  22569. );
  22570. } else {
  22571. make(
  22572. v[ i ][ k + 1 ],
  22573. v[ i + 1 ][ k + 1 ],
  22574. v[ i + 1 ][ k ],
  22575. materialIndex
  22576. );
  22577. }
  22578. }
  22579. }
  22580. }
  22581. // Angle around the Y axis, counter-clockwise when looking from above.
  22582. function azimuth( vector ) {
  22583. return Math.atan2( vector.z, - vector.x );
  22584. }
  22585. // Angle above the XZ plane.
  22586. function inclination( vector ) {
  22587. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22588. }
  22589. // Texture fixing helper. Spheres have some odd behaviours.
  22590. function correctUV( uv, vector, azimuth ) {
  22591. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  22592. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  22593. return uv.clone();
  22594. }
  22595. };
  22596. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22597. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  22598. // File:src/extras/geometries/DodecahedronGeometry.js
  22599. /**
  22600. * @author Abe Pazos / https://hamoid.com
  22601. */
  22602. THREE.DodecahedronGeometry = function ( radius, detail ) {
  22603. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22604. var r = 1 / t;
  22605. var vertices = [
  22606. // (±1, ±1, ±1)
  22607. - 1, - 1, - 1, - 1, - 1, 1,
  22608. - 1, 1, - 1, - 1, 1, 1,
  22609. 1, - 1, - 1, 1, - 1, 1,
  22610. 1, 1, - 1, 1, 1, 1,
  22611. // (0, ±1/φ, ±φ)
  22612. 0, - r, - t, 0, - r, t,
  22613. 0, r, - t, 0, r, t,
  22614. // (±1/φ, ±φ, 0)
  22615. - r, - t, 0, - r, t, 0,
  22616. r, - t, 0, r, t, 0,
  22617. // (±φ, 0, ±1/φ)
  22618. - t, 0, - r, t, 0, - r,
  22619. - t, 0, r, t, 0, r
  22620. ];
  22621. var indices = [
  22622. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22623. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22624. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22625. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22626. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22627. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22628. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22629. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22630. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22631. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22632. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22633. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22634. ];
  22635. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22636. this.type = 'DodecahedronGeometry';
  22637. this.parameters = {
  22638. radius: radius,
  22639. detail: detail
  22640. };
  22641. };
  22642. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22643. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  22644. // File:src/extras/geometries/IcosahedronGeometry.js
  22645. /**
  22646. * @author timothypratley / https://github.com/timothypratley
  22647. */
  22648. THREE.IcosahedronGeometry = function ( radius, detail ) {
  22649. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22650. var vertices = [
  22651. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22652. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22653. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22654. ];
  22655. var indices = [
  22656. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22657. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22658. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22659. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22660. ];
  22661. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22662. this.type = 'IcosahedronGeometry';
  22663. this.parameters = {
  22664. radius: radius,
  22665. detail: detail
  22666. };
  22667. };
  22668. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22669. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  22670. // File:src/extras/geometries/OctahedronGeometry.js
  22671. /**
  22672. * @author timothypratley / https://github.com/timothypratley
  22673. */
  22674. THREE.OctahedronGeometry = function ( radius, detail ) {
  22675. var vertices = [
  22676. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22677. ];
  22678. var indices = [
  22679. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  22680. ];
  22681. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22682. this.type = 'OctahedronGeometry';
  22683. this.parameters = {
  22684. radius: radius,
  22685. detail: detail
  22686. };
  22687. };
  22688. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22689. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  22690. // File:src/extras/geometries/TetrahedronGeometry.js
  22691. /**
  22692. * @author timothypratley / https://github.com/timothypratley
  22693. */
  22694. THREE.TetrahedronGeometry = function ( radius, detail ) {
  22695. var vertices = [
  22696. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22697. ];
  22698. var indices = [
  22699. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22700. ];
  22701. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22702. this.type = 'TetrahedronGeometry';
  22703. this.parameters = {
  22704. radius: radius,
  22705. detail: detail
  22706. };
  22707. };
  22708. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22709. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  22710. // File:src/extras/geometries/ParametricGeometry.js
  22711. /**
  22712. * @author zz85 / https://github.com/zz85
  22713. * Parametric Surfaces Geometry
  22714. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  22715. *
  22716. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  22717. *
  22718. */
  22719. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  22720. THREE.Geometry.call( this );
  22721. this.type = 'ParametricGeometry';
  22722. this.parameters = {
  22723. func: func,
  22724. slices: slices,
  22725. stacks: stacks
  22726. };
  22727. var verts = this.vertices;
  22728. var faces = this.faces;
  22729. var uvs = this.faceVertexUvs[ 0 ];
  22730. var i, j, p;
  22731. var u, v;
  22732. var sliceCount = slices + 1;
  22733. for ( i = 0; i <= stacks; i ++ ) {
  22734. v = i / stacks;
  22735. for ( j = 0; j <= slices; j ++ ) {
  22736. u = j / slices;
  22737. p = func( u, v );
  22738. verts.push( p );
  22739. }
  22740. }
  22741. var a, b, c, d;
  22742. var uva, uvb, uvc, uvd;
  22743. for ( i = 0; i < stacks; i ++ ) {
  22744. for ( j = 0; j < slices; j ++ ) {
  22745. a = i * sliceCount + j;
  22746. b = i * sliceCount + j + 1;
  22747. c = ( i + 1 ) * sliceCount + j + 1;
  22748. d = ( i + 1 ) * sliceCount + j;
  22749. uva = new THREE.Vector2( j / slices, i / stacks );
  22750. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  22751. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  22752. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  22753. faces.push( new THREE.Face3( a, b, d ) );
  22754. uvs.push( [ uva, uvb, uvd ] );
  22755. faces.push( new THREE.Face3( b, c, d ) );
  22756. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  22757. }
  22758. }
  22759. // console.log(this);
  22760. // magic bullet
  22761. // var diff = this.mergeVertices();
  22762. // console.log('removed ', diff, ' vertices by merging');
  22763. this.computeFaceNormals();
  22764. this.computeVertexNormals();
  22765. };
  22766. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22767. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  22768. // File:src/extras/geometries/WireframeGeometry.js
  22769. /**
  22770. * @author mrdoob / http://mrdoob.com/
  22771. */
  22772. THREE.WireframeGeometry = function ( geometry ) {
  22773. THREE.BufferGeometry.call( this );
  22774. var edge = [ 0, 0 ], hash = {};
  22775. function sortFunction( a, b ) {
  22776. return a - b;
  22777. }
  22778. var keys = [ 'a', 'b', 'c' ];
  22779. if ( geometry instanceof THREE.Geometry ) {
  22780. var vertices = geometry.vertices;
  22781. var faces = geometry.faces;
  22782. var numEdges = 0;
  22783. // allocate maximal size
  22784. var edges = new Uint32Array( 6 * faces.length );
  22785. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22786. var face = faces[ i ];
  22787. for ( var j = 0; j < 3; j ++ ) {
  22788. edge[ 0 ] = face[ keys[ j ] ];
  22789. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22790. edge.sort( sortFunction );
  22791. var key = edge.toString();
  22792. if ( hash[ key ] === undefined ) {
  22793. edges[ 2 * numEdges ] = edge[ 0 ];
  22794. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22795. hash[ key ] = true;
  22796. numEdges ++;
  22797. }
  22798. }
  22799. }
  22800. var coords = new Float32Array( numEdges * 2 * 3 );
  22801. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22802. for ( var j = 0; j < 2; j ++ ) {
  22803. var vertex = vertices[ edges [ 2 * i + j ] ];
  22804. var index = 6 * i + 3 * j;
  22805. coords[ index + 0 ] = vertex.x;
  22806. coords[ index + 1 ] = vertex.y;
  22807. coords[ index + 2 ] = vertex.z;
  22808. }
  22809. }
  22810. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22811. } else if ( geometry instanceof THREE.BufferGeometry ) {
  22812. if ( geometry.index !== null ) {
  22813. // Indexed BufferGeometry
  22814. var indices = geometry.index.array;
  22815. var vertices = geometry.attributes.position;
  22816. var drawcalls = geometry.drawcalls;
  22817. var numEdges = 0;
  22818. if ( drawcalls.length === 0 ) {
  22819. geometry.addGroup( 0, indices.length );
  22820. }
  22821. // allocate maximal size
  22822. var edges = new Uint32Array( 2 * indices.length );
  22823. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  22824. var drawcall = drawcalls[ o ];
  22825. var start = drawcall.start;
  22826. var count = drawcall.count;
  22827. for ( var i = start, il = start + count; i < il; i += 3 ) {
  22828. for ( var j = 0; j < 3; j ++ ) {
  22829. edge[ 0 ] = indices[ i + j ];
  22830. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  22831. edge.sort( sortFunction );
  22832. var key = edge.toString();
  22833. if ( hash[ key ] === undefined ) {
  22834. edges[ 2 * numEdges ] = edge[ 0 ];
  22835. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22836. hash[ key ] = true;
  22837. numEdges ++;
  22838. }
  22839. }
  22840. }
  22841. }
  22842. var coords = new Float32Array( numEdges * 2 * 3 );
  22843. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22844. for ( var j = 0; j < 2; j ++ ) {
  22845. var index = 6 * i + 3 * j;
  22846. var index2 = edges[ 2 * i + j ];
  22847. coords[ index + 0 ] = vertices.getX( index2 );
  22848. coords[ index + 1 ] = vertices.getY( index2 );
  22849. coords[ index + 2 ] = vertices.getZ( index2 );
  22850. }
  22851. }
  22852. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22853. } else {
  22854. // non-indexed BufferGeometry
  22855. var vertices = geometry.attributes.position.array;
  22856. var numEdges = vertices.length / 3;
  22857. var numTris = numEdges / 3;
  22858. var coords = new Float32Array( numEdges * 2 * 3 );
  22859. for ( var i = 0, l = numTris; i < l; i ++ ) {
  22860. for ( var j = 0; j < 3; j ++ ) {
  22861. var index = 18 * i + 6 * j;
  22862. var index1 = 9 * i + 3 * j;
  22863. coords[ index + 0 ] = vertices[ index1 ];
  22864. coords[ index + 1 ] = vertices[ index1 + 1 ];
  22865. coords[ index + 2 ] = vertices[ index1 + 2 ];
  22866. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  22867. coords[ index + 3 ] = vertices[ index2 ];
  22868. coords[ index + 4 ] = vertices[ index2 + 1 ];
  22869. coords[ index + 5 ] = vertices[ index2 + 2 ];
  22870. }
  22871. }
  22872. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22873. }
  22874. }
  22875. };
  22876. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22877. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  22878. // File:src/extras/helpers/AxisHelper.js
  22879. /**
  22880. * @author sroucheray / http://sroucheray.org/
  22881. * @author mrdoob / http://mrdoob.com/
  22882. */
  22883. THREE.AxisHelper = function ( size ) {
  22884. size = size || 1;
  22885. var vertices = new Float32Array( [
  22886. 0, 0, 0, size, 0, 0,
  22887. 0, 0, 0, 0, size, 0,
  22888. 0, 0, 0, 0, 0, size
  22889. ] );
  22890. var colors = new Float32Array( [
  22891. 1, 0, 0, 1, 0.6, 0,
  22892. 0, 1, 0, 0.6, 1, 0,
  22893. 0, 0, 1, 0, 0.6, 1
  22894. ] );
  22895. var geometry = new THREE.BufferGeometry();
  22896. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22897. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  22898. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  22899. THREE.LineSegments.call( this, geometry, material );
  22900. };
  22901. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  22902. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  22903. // File:src/extras/helpers/ArrowHelper.js
  22904. /**
  22905. * @author WestLangley / http://github.com/WestLangley
  22906. * @author zz85 / http://github.com/zz85
  22907. * @author bhouston / http://clara.io
  22908. *
  22909. * Creates an arrow for visualizing directions
  22910. *
  22911. * Parameters:
  22912. * dir - Vector3
  22913. * origin - Vector3
  22914. * length - Number
  22915. * color - color in hex value
  22916. * headLength - Number
  22917. * headWidth - Number
  22918. */
  22919. THREE.ArrowHelper = ( function () {
  22920. var lineGeometry = new THREE.Geometry();
  22921. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  22922. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  22923. coneGeometry.translate( 0, - 0.5, 0 );
  22924. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  22925. // dir is assumed to be normalized
  22926. THREE.Object3D.call( this );
  22927. if ( color === undefined ) color = 0xffff00;
  22928. if ( length === undefined ) length = 1;
  22929. if ( headLength === undefined ) headLength = 0.2 * length;
  22930. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22931. this.position.copy( origin );
  22932. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  22933. this.line.matrixAutoUpdate = false;
  22934. this.add( this.line );
  22935. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  22936. this.cone.matrixAutoUpdate = false;
  22937. this.add( this.cone );
  22938. this.setDirection( dir );
  22939. this.setLength( length, headLength, headWidth );
  22940. }
  22941. }() );
  22942. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  22943. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  22944. THREE.ArrowHelper.prototype.setDirection = ( function () {
  22945. var axis = new THREE.Vector3();
  22946. var radians;
  22947. return function setDirection( dir ) {
  22948. // dir is assumed to be normalized
  22949. if ( dir.y > 0.99999 ) {
  22950. this.quaternion.set( 0, 0, 0, 1 );
  22951. } else if ( dir.y < - 0.99999 ) {
  22952. this.quaternion.set( 1, 0, 0, 0 );
  22953. } else {
  22954. axis.set( dir.z, 0, - dir.x ).normalize();
  22955. radians = Math.acos( dir.y );
  22956. this.quaternion.setFromAxisAngle( axis, radians );
  22957. }
  22958. };
  22959. }() );
  22960. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  22961. if ( headLength === undefined ) headLength = 0.2 * length;
  22962. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22963. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  22964. this.line.updateMatrix();
  22965. this.cone.scale.set( headWidth, headLength, headWidth );
  22966. this.cone.position.y = length;
  22967. this.cone.updateMatrix();
  22968. };
  22969. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  22970. this.line.material.color.set( color );
  22971. this.cone.material.color.set( color );
  22972. };
  22973. // File:src/extras/helpers/BoxHelper.js
  22974. /**
  22975. * @author mrdoob / http://mrdoob.com/
  22976. */
  22977. THREE.BoxHelper = function ( object ) {
  22978. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  22979. var positions = new Float32Array( 8 * 3 );
  22980. var geometry = new THREE.BufferGeometry();
  22981. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22982. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  22983. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  22984. if ( object !== undefined ) {
  22985. this.update( object );
  22986. }
  22987. };
  22988. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  22989. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  22990. THREE.BoxHelper.prototype.update = ( function () {
  22991. var box = new THREE.Box3();
  22992. return function ( object ) {
  22993. box.setFromObject( object );
  22994. if ( box.empty() ) return;
  22995. var min = box.min;
  22996. var max = box.max;
  22997. /*
  22998. 5____4
  22999. 1/___0/|
  23000. | 6__|_7
  23001. 2/___3/
  23002. 0: max.x, max.y, max.z
  23003. 1: min.x, max.y, max.z
  23004. 2: min.x, min.y, max.z
  23005. 3: max.x, min.y, max.z
  23006. 4: max.x, max.y, min.z
  23007. 5: min.x, max.y, min.z
  23008. 6: min.x, min.y, min.z
  23009. 7: max.x, min.y, min.z
  23010. */
  23011. var position = this.geometry.attributes.position;
  23012. var array = position.array;
  23013. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23014. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23015. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23016. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23017. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23018. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23019. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23020. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23021. position.needsUpdate = true;
  23022. this.geometry.computeBoundingSphere();
  23023. }
  23024. } )();
  23025. // File:src/extras/helpers/BoundingBoxHelper.js
  23026. /**
  23027. * @author WestLangley / http://github.com/WestLangley
  23028. */
  23029. // a helper to show the world-axis-aligned bounding box for an object
  23030. THREE.BoundingBoxHelper = function ( object, hex ) {
  23031. var color = ( hex !== undefined ) ? hex : 0x888888;
  23032. this.object = object;
  23033. this.box = new THREE.Box3();
  23034. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  23035. };
  23036. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  23037. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  23038. THREE.BoundingBoxHelper.prototype.update = function () {
  23039. this.box.setFromObject( this.object );
  23040. this.box.size( this.scale );
  23041. this.box.center( this.position );
  23042. };
  23043. // File:src/extras/helpers/CameraHelper.js
  23044. /**
  23045. * @author alteredq / http://alteredqualia.com/
  23046. *
  23047. * - shows frustum, line of sight and up of the camera
  23048. * - suitable for fast updates
  23049. * - based on frustum visualization in lightgl.js shadowmap example
  23050. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  23051. */
  23052. THREE.CameraHelper = function ( camera ) {
  23053. var geometry = new THREE.Geometry();
  23054. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  23055. var pointMap = {};
  23056. // colors
  23057. var hexFrustum = 0xffaa00;
  23058. var hexCone = 0xff0000;
  23059. var hexUp = 0x00aaff;
  23060. var hexTarget = 0xffffff;
  23061. var hexCross = 0x333333;
  23062. // near
  23063. addLine( "n1", "n2", hexFrustum );
  23064. addLine( "n2", "n4", hexFrustum );
  23065. addLine( "n4", "n3", hexFrustum );
  23066. addLine( "n3", "n1", hexFrustum );
  23067. // far
  23068. addLine( "f1", "f2", hexFrustum );
  23069. addLine( "f2", "f4", hexFrustum );
  23070. addLine( "f4", "f3", hexFrustum );
  23071. addLine( "f3", "f1", hexFrustum );
  23072. // sides
  23073. addLine( "n1", "f1", hexFrustum );
  23074. addLine( "n2", "f2", hexFrustum );
  23075. addLine( "n3", "f3", hexFrustum );
  23076. addLine( "n4", "f4", hexFrustum );
  23077. // cone
  23078. addLine( "p", "n1", hexCone );
  23079. addLine( "p", "n2", hexCone );
  23080. addLine( "p", "n3", hexCone );
  23081. addLine( "p", "n4", hexCone );
  23082. // up
  23083. addLine( "u1", "u2", hexUp );
  23084. addLine( "u2", "u3", hexUp );
  23085. addLine( "u3", "u1", hexUp );
  23086. // target
  23087. addLine( "c", "t", hexTarget );
  23088. addLine( "p", "c", hexCross );
  23089. // cross
  23090. addLine( "cn1", "cn2", hexCross );
  23091. addLine( "cn3", "cn4", hexCross );
  23092. addLine( "cf1", "cf2", hexCross );
  23093. addLine( "cf3", "cf4", hexCross );
  23094. function addLine( a, b, hex ) {
  23095. addPoint( a, hex );
  23096. addPoint( b, hex );
  23097. }
  23098. function addPoint( id, hex ) {
  23099. geometry.vertices.push( new THREE.Vector3() );
  23100. geometry.colors.push( new THREE.Color( hex ) );
  23101. if ( pointMap[ id ] === undefined ) {
  23102. pointMap[ id ] = [];
  23103. }
  23104. pointMap[ id ].push( geometry.vertices.length - 1 );
  23105. }
  23106. THREE.LineSegments.call( this, geometry, material );
  23107. this.camera = camera;
  23108. this.camera.updateProjectionMatrix();
  23109. this.matrix = camera.matrixWorld;
  23110. this.matrixAutoUpdate = false;
  23111. this.pointMap = pointMap;
  23112. this.update();
  23113. };
  23114. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23115. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  23116. THREE.CameraHelper.prototype.update = function () {
  23117. var geometry, pointMap;
  23118. var vector = new THREE.Vector3();
  23119. var camera = new THREE.Camera();
  23120. function setPoint( point, x, y, z ) {
  23121. vector.set( x, y, z ).unproject( camera );
  23122. var points = pointMap[ point ];
  23123. if ( points !== undefined ) {
  23124. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23125. geometry.vertices[ points[ i ] ].copy( vector );
  23126. }
  23127. }
  23128. }
  23129. return function () {
  23130. geometry = this.geometry;
  23131. pointMap = this.pointMap;
  23132. var w = 1, h = 1;
  23133. // we need just camera projection matrix
  23134. // world matrix must be identity
  23135. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23136. // center / target
  23137. setPoint( "c", 0, 0, - 1 );
  23138. setPoint( "t", 0, 0, 1 );
  23139. // near
  23140. setPoint( "n1", - w, - h, - 1 );
  23141. setPoint( "n2", w, - h, - 1 );
  23142. setPoint( "n3", - w, h, - 1 );
  23143. setPoint( "n4", w, h, - 1 );
  23144. // far
  23145. setPoint( "f1", - w, - h, 1 );
  23146. setPoint( "f2", w, - h, 1 );
  23147. setPoint( "f3", - w, h, 1 );
  23148. setPoint( "f4", w, h, 1 );
  23149. // up
  23150. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  23151. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  23152. setPoint( "u3", 0, h * 2, - 1 );
  23153. // cross
  23154. setPoint( "cf1", - w, 0, 1 );
  23155. setPoint( "cf2", w, 0, 1 );
  23156. setPoint( "cf3", 0, - h, 1 );
  23157. setPoint( "cf4", 0, h, 1 );
  23158. setPoint( "cn1", - w, 0, - 1 );
  23159. setPoint( "cn2", w, 0, - 1 );
  23160. setPoint( "cn3", 0, - h, - 1 );
  23161. setPoint( "cn4", 0, h, - 1 );
  23162. geometry.verticesNeedUpdate = true;
  23163. };
  23164. }();
  23165. // File:src/extras/helpers/DirectionalLightHelper.js
  23166. /**
  23167. * @author alteredq / http://alteredqualia.com/
  23168. * @author mrdoob / http://mrdoob.com/
  23169. * @author WestLangley / http://github.com/WestLangley
  23170. */
  23171. THREE.DirectionalLightHelper = function ( light, size ) {
  23172. THREE.Object3D.call( this );
  23173. this.light = light;
  23174. this.light.updateMatrixWorld();
  23175. this.matrix = light.matrixWorld;
  23176. this.matrixAutoUpdate = false;
  23177. size = size || 1;
  23178. var geometry = new THREE.Geometry();
  23179. geometry.vertices.push(
  23180. new THREE.Vector3( - size, size, 0 ),
  23181. new THREE.Vector3( size, size, 0 ),
  23182. new THREE.Vector3( size, - size, 0 ),
  23183. new THREE.Vector3( - size, - size, 0 ),
  23184. new THREE.Vector3( - size, size, 0 )
  23185. );
  23186. var material = new THREE.LineBasicMaterial( { fog: false } );
  23187. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23188. this.lightPlane = new THREE.Line( geometry, material );
  23189. this.add( this.lightPlane );
  23190. geometry = new THREE.Geometry();
  23191. geometry.vertices.push(
  23192. new THREE.Vector3(),
  23193. new THREE.Vector3()
  23194. );
  23195. material = new THREE.LineBasicMaterial( { fog: false } );
  23196. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23197. this.targetLine = new THREE.Line( geometry, material );
  23198. this.add( this.targetLine );
  23199. this.update();
  23200. };
  23201. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23202. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  23203. THREE.DirectionalLightHelper.prototype.dispose = function () {
  23204. this.lightPlane.geometry.dispose();
  23205. this.lightPlane.material.dispose();
  23206. this.targetLine.geometry.dispose();
  23207. this.targetLine.material.dispose();
  23208. };
  23209. THREE.DirectionalLightHelper.prototype.update = function () {
  23210. var v1 = new THREE.Vector3();
  23211. var v2 = new THREE.Vector3();
  23212. var v3 = new THREE.Vector3();
  23213. return function () {
  23214. v1.setFromMatrixPosition( this.light.matrixWorld );
  23215. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23216. v3.subVectors( v2, v1 );
  23217. this.lightPlane.lookAt( v3 );
  23218. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23219. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  23220. this.targetLine.geometry.verticesNeedUpdate = true;
  23221. this.targetLine.material.color.copy( this.lightPlane.material.color );
  23222. };
  23223. }();
  23224. // File:src/extras/helpers/EdgesHelper.js
  23225. /**
  23226. * @author WestLangley / http://github.com/WestLangley
  23227. * @param object THREE.Mesh whose geometry will be used
  23228. * @param hex line color
  23229. * @param thresholdAngle the minimum angle (in degrees),
  23230. * between the face normals of adjacent faces,
  23231. * that is required to render an edge. A value of 10 means
  23232. * an edge is only rendered if the angle is at least 10 degrees.
  23233. */
  23234. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  23235. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23236. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  23237. this.matrix = object.matrixWorld;
  23238. this.matrixAutoUpdate = false;
  23239. };
  23240. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23241. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  23242. // File:src/extras/helpers/FaceNormalsHelper.js
  23243. /**
  23244. * @author mrdoob / http://mrdoob.com/
  23245. * @author WestLangley / http://github.com/WestLangley
  23246. */
  23247. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  23248. // FaceNormalsHelper only supports THREE.Geometry
  23249. this.object = object;
  23250. this.size = ( size !== undefined ) ? size : 1;
  23251. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23252. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23253. //
  23254. var nNormals = 0;
  23255. var objGeometry = this.object.geometry;
  23256. if ( objGeometry instanceof THREE.Geometry ) {
  23257. nNormals = objGeometry.faces.length;
  23258. } else {
  23259. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23260. }
  23261. //
  23262. var geometry = new THREE.BufferGeometry();
  23263. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23264. geometry.addAttribute( 'position', positions );
  23265. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23266. //
  23267. this.matrixAutoUpdate = false;
  23268. this.update();
  23269. };
  23270. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23271. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  23272. THREE.FaceNormalsHelper.prototype.update = ( function () {
  23273. var v1 = new THREE.Vector3();
  23274. var v2 = new THREE.Vector3();
  23275. var normalMatrix = new THREE.Matrix3();
  23276. return function update() {
  23277. this.object.updateMatrixWorld( true );
  23278. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23279. var matrixWorld = this.object.matrixWorld;
  23280. var position = this.geometry.attributes.position;
  23281. //
  23282. var objGeometry = this.object.geometry;
  23283. var vertices = objGeometry.vertices;
  23284. var faces = objGeometry.faces;
  23285. var idx = 0;
  23286. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23287. var face = faces[ i ];
  23288. var normal = face.normal;
  23289. v1.copy( vertices[ face.a ] )
  23290. .add( vertices[ face.b ] )
  23291. .add( vertices[ face.c ] )
  23292. .divideScalar( 3 )
  23293. .applyMatrix4( matrixWorld );
  23294. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23295. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23296. idx = idx + 1;
  23297. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23298. idx = idx + 1;
  23299. }
  23300. position.needsUpdate = true;
  23301. return this;
  23302. }
  23303. }() );
  23304. // File:src/extras/helpers/GridHelper.js
  23305. /**
  23306. * @author mrdoob / http://mrdoob.com/
  23307. */
  23308. THREE.GridHelper = function ( size, step ) {
  23309. var geometry = new THREE.Geometry();
  23310. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23311. this.color1 = new THREE.Color( 0x444444 );
  23312. this.color2 = new THREE.Color( 0x888888 );
  23313. for ( var i = - size; i <= size; i += step ) {
  23314. geometry.vertices.push(
  23315. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  23316. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  23317. );
  23318. var color = i === 0 ? this.color1 : this.color2;
  23319. geometry.colors.push( color, color, color, color );
  23320. }
  23321. THREE.LineSegments.call( this, geometry, material );
  23322. };
  23323. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23324. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  23325. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  23326. this.color1.set( colorCenterLine );
  23327. this.color2.set( colorGrid );
  23328. this.geometry.colorsNeedUpdate = true;
  23329. };
  23330. // File:src/extras/helpers/HemisphereLightHelper.js
  23331. /**
  23332. * @author alteredq / http://alteredqualia.com/
  23333. * @author mrdoob / http://mrdoob.com/
  23334. */
  23335. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  23336. THREE.Object3D.call( this );
  23337. this.light = light;
  23338. this.light.updateMatrixWorld();
  23339. this.matrix = light.matrixWorld;
  23340. this.matrixAutoUpdate = false;
  23341. this.colors = [ new THREE.Color(), new THREE.Color() ];
  23342. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23343. geometry.rotateX( - Math.PI / 2 );
  23344. for ( var i = 0, il = 8; i < il; i ++ ) {
  23345. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  23346. }
  23347. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  23348. this.lightSphere = new THREE.Mesh( geometry, material );
  23349. this.add( this.lightSphere );
  23350. this.update();
  23351. };
  23352. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23353. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  23354. THREE.HemisphereLightHelper.prototype.dispose = function () {
  23355. this.lightSphere.geometry.dispose();
  23356. this.lightSphere.material.dispose();
  23357. };
  23358. THREE.HemisphereLightHelper.prototype.update = function () {
  23359. var vector = new THREE.Vector3();
  23360. return function () {
  23361. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  23362. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  23363. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  23364. this.lightSphere.geometry.colorsNeedUpdate = true;
  23365. }
  23366. }();
  23367. // File:src/extras/helpers/PointLightHelper.js
  23368. /**
  23369. * @author alteredq / http://alteredqualia.com/
  23370. * @author mrdoob / http://mrdoob.com/
  23371. */
  23372. THREE.PointLightHelper = function ( light, sphereSize ) {
  23373. this.light = light;
  23374. this.light.updateMatrixWorld();
  23375. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23376. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23377. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23378. THREE.Mesh.call( this, geometry, material );
  23379. this.matrix = this.light.matrixWorld;
  23380. this.matrixAutoUpdate = false;
  23381. /*
  23382. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  23383. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  23384. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  23385. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  23386. var d = light.distance;
  23387. if ( d === 0.0 ) {
  23388. this.lightDistance.visible = false;
  23389. } else {
  23390. this.lightDistance.scale.set( d, d, d );
  23391. }
  23392. this.add( this.lightDistance );
  23393. */
  23394. };
  23395. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  23396. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  23397. THREE.PointLightHelper.prototype.dispose = function () {
  23398. this.geometry.dispose();
  23399. this.material.dispose();
  23400. };
  23401. THREE.PointLightHelper.prototype.update = function () {
  23402. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23403. /*
  23404. var d = this.light.distance;
  23405. if ( d === 0.0 ) {
  23406. this.lightDistance.visible = false;
  23407. } else {
  23408. this.lightDistance.visible = true;
  23409. this.lightDistance.scale.set( d, d, d );
  23410. }
  23411. */
  23412. };
  23413. // File:src/extras/helpers/SkeletonHelper.js
  23414. /**
  23415. * @author Sean Griffin / http://twitter.com/sgrif
  23416. * @author Michael Guerrero / http://realitymeltdown.com
  23417. * @author mrdoob / http://mrdoob.com/
  23418. * @author ikerr / http://verold.com
  23419. */
  23420. THREE.SkeletonHelper = function ( object ) {
  23421. this.bones = this.getBoneList( object );
  23422. var geometry = new THREE.Geometry();
  23423. for ( var i = 0; i < this.bones.length; i ++ ) {
  23424. var bone = this.bones[ i ];
  23425. if ( bone.parent instanceof THREE.Bone ) {
  23426. geometry.vertices.push( new THREE.Vector3() );
  23427. geometry.vertices.push( new THREE.Vector3() );
  23428. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  23429. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  23430. }
  23431. }
  23432. geometry.dynamic = true;
  23433. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23434. THREE.LineSegments.call( this, geometry, material );
  23435. this.root = object;
  23436. this.matrix = object.matrixWorld;
  23437. this.matrixAutoUpdate = false;
  23438. this.update();
  23439. };
  23440. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23441. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  23442. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  23443. var boneList = [];
  23444. if ( object instanceof THREE.Bone ) {
  23445. boneList.push( object );
  23446. }
  23447. for ( var i = 0; i < object.children.length; i ++ ) {
  23448. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23449. }
  23450. return boneList;
  23451. };
  23452. THREE.SkeletonHelper.prototype.update = function () {
  23453. var geometry = this.geometry;
  23454. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  23455. var boneMatrix = new THREE.Matrix4();
  23456. var j = 0;
  23457. for ( var i = 0; i < this.bones.length; i ++ ) {
  23458. var bone = this.bones[ i ];
  23459. if ( bone.parent instanceof THREE.Bone ) {
  23460. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23461. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  23462. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23463. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  23464. j += 2;
  23465. }
  23466. }
  23467. geometry.verticesNeedUpdate = true;
  23468. geometry.computeBoundingSphere();
  23469. };
  23470. // File:src/extras/helpers/SpotLightHelper.js
  23471. /**
  23472. * @author alteredq / http://alteredqualia.com/
  23473. * @author mrdoob / http://mrdoob.com/
  23474. * @author WestLangley / http://github.com/WestLangley
  23475. */
  23476. THREE.SpotLightHelper = function ( light ) {
  23477. THREE.Object3D.call( this );
  23478. this.light = light;
  23479. this.light.updateMatrixWorld();
  23480. this.matrix = light.matrixWorld;
  23481. this.matrixAutoUpdate = false;
  23482. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  23483. geometry.translate( 0, - 0.5, 0 );
  23484. geometry.rotateX( - Math.PI / 2 );
  23485. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23486. this.cone = new THREE.Mesh( geometry, material );
  23487. this.add( this.cone );
  23488. this.update();
  23489. };
  23490. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23491. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  23492. THREE.SpotLightHelper.prototype.dispose = function () {
  23493. this.cone.geometry.dispose();
  23494. this.cone.material.dispose();
  23495. };
  23496. THREE.SpotLightHelper.prototype.update = function () {
  23497. var vector = new THREE.Vector3();
  23498. var vector2 = new THREE.Vector3();
  23499. return function () {
  23500. var coneLength = this.light.distance ? this.light.distance : 10000;
  23501. var coneWidth = coneLength * Math.tan( this.light.angle );
  23502. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23503. vector.setFromMatrixPosition( this.light.matrixWorld );
  23504. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23505. this.cone.lookAt( vector2.sub( vector ) );
  23506. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23507. };
  23508. }();
  23509. // File:src/extras/helpers/VertexNormalsHelper.js
  23510. /**
  23511. * @author mrdoob / http://mrdoob.com/
  23512. * @author WestLangley / http://github.com/WestLangley
  23513. */
  23514. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  23515. this.object = object;
  23516. this.size = ( size !== undefined ) ? size : 1;
  23517. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23518. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23519. //
  23520. var nNormals = 0;
  23521. var objGeometry = this.object.geometry;
  23522. if ( objGeometry instanceof THREE.Geometry ) {
  23523. nNormals = objGeometry.faces.length * 3;
  23524. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23525. nNormals = objGeometry.attributes.normal.count
  23526. }
  23527. //
  23528. var geometry = new THREE.BufferGeometry();
  23529. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23530. geometry.addAttribute( 'position', positions );
  23531. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23532. //
  23533. this.matrixAutoUpdate = false;
  23534. this.update();
  23535. };
  23536. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23537. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  23538. THREE.VertexNormalsHelper.prototype.update = ( function () {
  23539. var v1 = new THREE.Vector3();
  23540. var v2 = new THREE.Vector3();
  23541. var normalMatrix = new THREE.Matrix3();
  23542. return function update() {
  23543. var keys = [ 'a', 'b', 'c' ];
  23544. this.object.updateMatrixWorld( true );
  23545. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23546. var matrixWorld = this.object.matrixWorld;
  23547. var position = this.geometry.attributes.position;
  23548. //
  23549. var objGeometry = this.object.geometry;
  23550. if ( objGeometry instanceof THREE.Geometry ) {
  23551. var vertices = objGeometry.vertices;
  23552. var faces = objGeometry.faces;
  23553. var idx = 0;
  23554. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23555. var face = faces[ i ];
  23556. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23557. var vertex = vertices[ face[ keys[ j ] ] ];
  23558. var normal = face.vertexNormals[ j ];
  23559. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23560. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23561. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23562. idx = idx + 1;
  23563. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23564. idx = idx + 1;
  23565. }
  23566. }
  23567. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23568. var objPos = objGeometry.attributes.position;
  23569. var objNorm = objGeometry.attributes.normal;
  23570. var idx = 0;
  23571. // for simplicity, ignore index and drawcalls, and render every normal
  23572. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23573. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23574. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23575. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23576. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23577. idx = idx + 1;
  23578. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23579. idx = idx + 1;
  23580. }
  23581. }
  23582. position.needsUpdate = true;
  23583. return this;
  23584. }
  23585. }() );
  23586. // File:src/extras/helpers/WireframeHelper.js
  23587. /**
  23588. * @author mrdoob / http://mrdoob.com/
  23589. */
  23590. THREE.WireframeHelper = function ( object, hex ) {
  23591. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23592. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  23593. this.matrix = object.matrixWorld;
  23594. this.matrixAutoUpdate = false;
  23595. };
  23596. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23597. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  23598. // File:src/extras/objects/ImmediateRenderObject.js
  23599. /**
  23600. * @author alteredq / http://alteredqualia.com/
  23601. */
  23602. THREE.ImmediateRenderObject = function ( material ) {
  23603. THREE.Object3D.call( this );
  23604. this.material = material;
  23605. this.render = function ( renderCallback ) {};
  23606. };
  23607. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  23608. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  23609. // File:src/extras/objects/MorphBlendMesh.js
  23610. /**
  23611. * @author alteredq / http://alteredqualia.com/
  23612. */
  23613. THREE.MorphBlendMesh = function( geometry, material ) {
  23614. THREE.Mesh.call( this, geometry, material );
  23615. this.animationsMap = {};
  23616. this.animationsList = [];
  23617. // prepare default animation
  23618. // (all frames played together in 1 second)
  23619. var numFrames = this.geometry.morphTargets.length;
  23620. var name = "__default";
  23621. var startFrame = 0;
  23622. var endFrame = numFrames - 1;
  23623. var fps = numFrames / 1;
  23624. this.createAnimation( name, startFrame, endFrame, fps );
  23625. this.setAnimationWeight( name, 1 );
  23626. };
  23627. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  23628. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  23629. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23630. var animation = {
  23631. start: start,
  23632. end: end,
  23633. length: end - start + 1,
  23634. fps: fps,
  23635. duration: ( end - start ) / fps,
  23636. lastFrame: 0,
  23637. currentFrame: 0,
  23638. active: false,
  23639. time: 0,
  23640. direction: 1,
  23641. weight: 1,
  23642. directionBackwards: false,
  23643. mirroredLoop: false
  23644. };
  23645. this.animationsMap[ name ] = animation;
  23646. this.animationsList.push( animation );
  23647. };
  23648. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23649. var pattern = /([a-z]+)_?(\d+)/;
  23650. var firstAnimation, frameRanges = {};
  23651. var geometry = this.geometry;
  23652. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23653. var morph = geometry.morphTargets[ i ];
  23654. var chunks = morph.name.match( pattern );
  23655. if ( chunks && chunks.length > 1 ) {
  23656. var name = chunks[ 1 ];
  23657. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23658. var range = frameRanges[ name ];
  23659. if ( i < range.start ) range.start = i;
  23660. if ( i > range.end ) range.end = i;
  23661. if ( ! firstAnimation ) firstAnimation = name;
  23662. }
  23663. }
  23664. for ( var name in frameRanges ) {
  23665. var range = frameRanges[ name ];
  23666. this.createAnimation( name, range.start, range.end, fps );
  23667. }
  23668. this.firstAnimation = firstAnimation;
  23669. };
  23670. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23671. var animation = this.animationsMap[ name ];
  23672. if ( animation ) {
  23673. animation.direction = 1;
  23674. animation.directionBackwards = false;
  23675. }
  23676. };
  23677. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23678. var animation = this.animationsMap[ name ];
  23679. if ( animation ) {
  23680. animation.direction = - 1;
  23681. animation.directionBackwards = true;
  23682. }
  23683. };
  23684. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23685. var animation = this.animationsMap[ name ];
  23686. if ( animation ) {
  23687. animation.fps = fps;
  23688. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23689. }
  23690. };
  23691. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23692. var animation = this.animationsMap[ name ];
  23693. if ( animation ) {
  23694. animation.duration = duration;
  23695. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23696. }
  23697. };
  23698. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23699. var animation = this.animationsMap[ name ];
  23700. if ( animation ) {
  23701. animation.weight = weight;
  23702. }
  23703. };
  23704. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23705. var animation = this.animationsMap[ name ];
  23706. if ( animation ) {
  23707. animation.time = time;
  23708. }
  23709. };
  23710. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23711. var time = 0;
  23712. var animation = this.animationsMap[ name ];
  23713. if ( animation ) {
  23714. time = animation.time;
  23715. }
  23716. return time;
  23717. };
  23718. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23719. var duration = - 1;
  23720. var animation = this.animationsMap[ name ];
  23721. if ( animation ) {
  23722. duration = animation.duration;
  23723. }
  23724. return duration;
  23725. };
  23726. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23727. var animation = this.animationsMap[ name ];
  23728. if ( animation ) {
  23729. animation.time = 0;
  23730. animation.active = true;
  23731. } else {
  23732. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23733. }
  23734. };
  23735. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23736. var animation = this.animationsMap[ name ];
  23737. if ( animation ) {
  23738. animation.active = false;
  23739. }
  23740. };
  23741. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  23742. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23743. var animation = this.animationsList[ i ];
  23744. if ( ! animation.active ) continue;
  23745. var frameTime = animation.duration / animation.length;
  23746. animation.time += animation.direction * delta;
  23747. if ( animation.mirroredLoop ) {
  23748. if ( animation.time > animation.duration || animation.time < 0 ) {
  23749. animation.direction *= - 1;
  23750. if ( animation.time > animation.duration ) {
  23751. animation.time = animation.duration;
  23752. animation.directionBackwards = true;
  23753. }
  23754. if ( animation.time < 0 ) {
  23755. animation.time = 0;
  23756. animation.directionBackwards = false;
  23757. }
  23758. }
  23759. } else {
  23760. animation.time = animation.time % animation.duration;
  23761. if ( animation.time < 0 ) animation.time += animation.duration;
  23762. }
  23763. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23764. var weight = animation.weight;
  23765. if ( keyframe !== animation.currentFrame ) {
  23766. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23767. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23768. this.morphTargetInfluences[ keyframe ] = 0;
  23769. animation.lastFrame = animation.currentFrame;
  23770. animation.currentFrame = keyframe;
  23771. }
  23772. var mix = ( animation.time % frameTime ) / frameTime;
  23773. if ( animation.directionBackwards ) mix = 1 - mix;
  23774. if ( animation.currentFrame !== animation.lastFrame ) {
  23775. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23776. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23777. } else {
  23778. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23779. }
  23780. }
  23781. };