three.js 964 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, (function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. /**
  51. * https://github.com/mrdoob/eventdispatcher.js/
  52. */
  53. function EventDispatcher() {}
  54. Object.assign( EventDispatcher.prototype, {
  55. addEventListener: function ( type, listener ) {
  56. if ( this._listeners === undefined ) this._listeners = {};
  57. var listeners = this._listeners;
  58. if ( listeners[ type ] === undefined ) {
  59. listeners[ type ] = [];
  60. }
  61. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  62. listeners[ type ].push( listener );
  63. }
  64. },
  65. hasEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return false;
  67. var listeners = this._listeners;
  68. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  69. return true;
  70. }
  71. return false;
  72. },
  73. removeEventListener: function ( type, listener ) {
  74. if ( this._listeners === undefined ) return;
  75. var listeners = this._listeners;
  76. var listenerArray = listeners[ type ];
  77. if ( listenerArray !== undefined ) {
  78. var index = listenerArray.indexOf( listener );
  79. if ( index !== - 1 ) {
  80. listenerArray.splice( index, 1 );
  81. }
  82. }
  83. },
  84. dispatchEvent: function ( event ) {
  85. if ( this._listeners === undefined ) return;
  86. var listeners = this._listeners;
  87. var listenerArray = listeners[ event.type ];
  88. if ( listenerArray !== undefined ) {
  89. event.target = this;
  90. var array = [], i = 0;
  91. var length = listenerArray.length;
  92. for ( i = 0; i < length; i ++ ) {
  93. array[ i ] = listenerArray[ i ];
  94. }
  95. for ( i = 0; i < length; i ++ ) {
  96. array[ i ].call( this, event );
  97. }
  98. }
  99. }
  100. } );
  101. var REVISION = '81dev';
  102. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  103. var CullFaceNone = 0;
  104. var CullFaceBack = 1;
  105. var CullFaceFront = 2;
  106. var CullFaceFrontBack = 3;
  107. var FrontFaceDirectionCW = 0;
  108. var FrontFaceDirectionCCW = 1;
  109. var BasicShadowMap = 0;
  110. var PCFShadowMap = 1;
  111. var PCFSoftShadowMap = 2;
  112. var FrontSide = 0;
  113. var BackSide = 1;
  114. var DoubleSide = 2;
  115. var FlatShading = 1;
  116. var SmoothShading = 2;
  117. var NoColors = 0;
  118. var FaceColors = 1;
  119. var VertexColors = 2;
  120. var NoBlending = 0;
  121. var NormalBlending = 1;
  122. var AdditiveBlending = 2;
  123. var SubtractiveBlending = 3;
  124. var MultiplyBlending = 4;
  125. var CustomBlending = 5;
  126. var AddEquation = 100;
  127. var SubtractEquation = 101;
  128. var ReverseSubtractEquation = 102;
  129. var MinEquation = 103;
  130. var MaxEquation = 104;
  131. var ZeroFactor = 200;
  132. var OneFactor = 201;
  133. var SrcColorFactor = 202;
  134. var OneMinusSrcColorFactor = 203;
  135. var SrcAlphaFactor = 204;
  136. var OneMinusSrcAlphaFactor = 205;
  137. var DstAlphaFactor = 206;
  138. var OneMinusDstAlphaFactor = 207;
  139. var DstColorFactor = 208;
  140. var OneMinusDstColorFactor = 209;
  141. var SrcAlphaSaturateFactor = 210;
  142. var NeverDepth = 0;
  143. var AlwaysDepth = 1;
  144. var LessDepth = 2;
  145. var LessEqualDepth = 3;
  146. var EqualDepth = 4;
  147. var GreaterEqualDepth = 5;
  148. var GreaterDepth = 6;
  149. var NotEqualDepth = 7;
  150. var MultiplyOperation = 0;
  151. var MixOperation = 1;
  152. var AddOperation = 2;
  153. var NoToneMapping = 0;
  154. var LinearToneMapping = 1;
  155. var ReinhardToneMapping = 2;
  156. var Uncharted2ToneMapping = 3;
  157. var CineonToneMapping = 4;
  158. var UVMapping = 300;
  159. var CubeReflectionMapping = 301;
  160. var CubeRefractionMapping = 302;
  161. var EquirectangularReflectionMapping = 303;
  162. var EquirectangularRefractionMapping = 304;
  163. var SphericalReflectionMapping = 305;
  164. var CubeUVReflectionMapping = 306;
  165. var CubeUVRefractionMapping = 307;
  166. var RepeatWrapping = 1000;
  167. var ClampToEdgeWrapping = 1001;
  168. var MirroredRepeatWrapping = 1002;
  169. var NearestFilter = 1003;
  170. var NearestMipMapNearestFilter = 1004;
  171. var NearestMipMapLinearFilter = 1005;
  172. var LinearFilter = 1006;
  173. var LinearMipMapNearestFilter = 1007;
  174. var LinearMipMapLinearFilter = 1008;
  175. var UnsignedByteType = 1009;
  176. var ByteType = 1010;
  177. var ShortType = 1011;
  178. var UnsignedShortType = 1012;
  179. var IntType = 1013;
  180. var UnsignedIntType = 1014;
  181. var FloatType = 1015;
  182. var HalfFloatType = 1016;
  183. var UnsignedShort4444Type = 1017;
  184. var UnsignedShort5551Type = 1018;
  185. var UnsignedShort565Type = 1019;
  186. var UnsignedInt248Type = 1020;
  187. var AlphaFormat = 1021;
  188. var RGBFormat = 1022;
  189. var RGBAFormat = 1023;
  190. var LuminanceFormat = 1024;
  191. var LuminanceAlphaFormat = 1025;
  192. var RGBEFormat = RGBAFormat;
  193. var DepthFormat = 1026;
  194. var DepthStencilFormat = 1027;
  195. var RGB_S3TC_DXT1_Format = 2001;
  196. var RGBA_S3TC_DXT1_Format = 2002;
  197. var RGBA_S3TC_DXT3_Format = 2003;
  198. var RGBA_S3TC_DXT5_Format = 2004;
  199. var RGB_PVRTC_4BPPV1_Format = 2100;
  200. var RGB_PVRTC_2BPPV1_Format = 2101;
  201. var RGBA_PVRTC_4BPPV1_Format = 2102;
  202. var RGBA_PVRTC_2BPPV1_Format = 2103;
  203. var RGB_ETC1_Format = 2151;
  204. var LoopOnce = 2200;
  205. var LoopRepeat = 2201;
  206. var LoopPingPong = 2202;
  207. var InterpolateDiscrete = 2300;
  208. var InterpolateLinear = 2301;
  209. var InterpolateSmooth = 2302;
  210. var ZeroCurvatureEnding = 2400;
  211. var ZeroSlopeEnding = 2401;
  212. var WrapAroundEnding = 2402;
  213. var TrianglesDrawMode = 0;
  214. var TriangleStripDrawMode = 1;
  215. var TriangleFanDrawMode = 2;
  216. var LinearEncoding = 3000;
  217. var sRGBEncoding = 3001;
  218. var GammaEncoding = 3007;
  219. var RGBEEncoding = 3002;
  220. var LogLuvEncoding = 3003;
  221. var RGBM7Encoding = 3004;
  222. var RGBM16Encoding = 3005;
  223. var RGBDEncoding = 3006;
  224. var BasicDepthPacking = 3200;
  225. var RGBADepthPacking = 3201;
  226. /**
  227. * @author alteredq / http://alteredqualia.com/
  228. * @author mrdoob / http://mrdoob.com/
  229. */
  230. exports.Math = {
  231. DEG2RAD: Math.PI / 180,
  232. RAD2DEG: 180 / Math.PI,
  233. generateUUID: function () {
  234. // http://www.broofa.com/Tools/Math.uuid.htm
  235. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  236. var uuid = new Array( 36 );
  237. var rnd = 0, r;
  238. return function generateUUID() {
  239. for ( var i = 0; i < 36; i ++ ) {
  240. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  241. uuid[ i ] = '-';
  242. } else if ( i === 14 ) {
  243. uuid[ i ] = '4';
  244. } else {
  245. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  246. r = rnd & 0xf;
  247. rnd = rnd >> 4;
  248. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  249. }
  250. }
  251. return uuid.join( '' );
  252. };
  253. }(),
  254. clamp: function ( value, min, max ) {
  255. return Math.max( min, Math.min( max, value ) );
  256. },
  257. // compute euclidian modulo of m % n
  258. // https://en.wikipedia.org/wiki/Modulo_operation
  259. euclideanModulo: function ( n, m ) {
  260. return ( ( n % m ) + m ) % m;
  261. },
  262. // Linear mapping from range <a1, a2> to range <b1, b2>
  263. mapLinear: function ( x, a1, a2, b1, b2 ) {
  264. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  265. },
  266. // http://en.wikipedia.org/wiki/Smoothstep
  267. smoothstep: function ( x, min, max ) {
  268. if ( x <= min ) return 0;
  269. if ( x >= max ) return 1;
  270. x = ( x - min ) / ( max - min );
  271. return x * x * ( 3 - 2 * x );
  272. },
  273. smootherstep: function ( x, min, max ) {
  274. if ( x <= min ) return 0;
  275. if ( x >= max ) return 1;
  276. x = ( x - min ) / ( max - min );
  277. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  278. },
  279. random16: function () {
  280. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  281. return Math.random();
  282. },
  283. // Random integer from <low, high> interval
  284. randInt: function ( low, high ) {
  285. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  286. },
  287. // Random float from <low, high> interval
  288. randFloat: function ( low, high ) {
  289. return low + Math.random() * ( high - low );
  290. },
  291. // Random float from <-range/2, range/2> interval
  292. randFloatSpread: function ( range ) {
  293. return range * ( 0.5 - Math.random() );
  294. },
  295. degToRad: function ( degrees ) {
  296. return degrees * exports.Math.DEG2RAD;
  297. },
  298. radToDeg: function ( radians ) {
  299. return radians * exports.Math.RAD2DEG;
  300. },
  301. isPowerOfTwo: function ( value ) {
  302. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  303. },
  304. nearestPowerOfTwo: function ( value ) {
  305. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  306. },
  307. nextPowerOfTwo: function ( value ) {
  308. value --;
  309. value |= value >> 1;
  310. value |= value >> 2;
  311. value |= value >> 4;
  312. value |= value >> 8;
  313. value |= value >> 16;
  314. value ++;
  315. return value;
  316. }
  317. };
  318. /**
  319. * @author mrdoob / http://mrdoob.com/
  320. * @author philogb / http://blog.thejit.org/
  321. * @author egraether / http://egraether.com/
  322. * @author zz85 / http://www.lab4games.net/zz85/blog
  323. */
  324. function Vector2( x, y ) {
  325. this.x = x || 0;
  326. this.y = y || 0;
  327. }
  328. Vector2.prototype = {
  329. constructor: Vector2,
  330. isVector2: true,
  331. get width() {
  332. return this.x;
  333. },
  334. set width( value ) {
  335. this.x = value;
  336. },
  337. get height() {
  338. return this.y;
  339. },
  340. set height( value ) {
  341. this.y = value;
  342. },
  343. //
  344. set: function ( x, y ) {
  345. this.x = x;
  346. this.y = y;
  347. return this;
  348. },
  349. setScalar: function ( scalar ) {
  350. this.x = scalar;
  351. this.y = scalar;
  352. return this;
  353. },
  354. setX: function ( x ) {
  355. this.x = x;
  356. return this;
  357. },
  358. setY: function ( y ) {
  359. this.y = y;
  360. return this;
  361. },
  362. setComponent: function ( index, value ) {
  363. switch ( index ) {
  364. case 0: this.x = value; break;
  365. case 1: this.y = value; break;
  366. default: throw new Error( 'index is out of range: ' + index );
  367. }
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. if ( isFinite( scalar ) ) {
  434. this.x *= scalar;
  435. this.y *= scalar;
  436. } else {
  437. this.x = 0;
  438. this.y = 0;
  439. }
  440. return this;
  441. },
  442. divide: function ( v ) {
  443. this.x /= v.x;
  444. this.y /= v.y;
  445. return this;
  446. },
  447. divideScalar: function ( scalar ) {
  448. return this.multiplyScalar( 1 / scalar );
  449. },
  450. min: function ( v ) {
  451. this.x = Math.min( this.x, v.x );
  452. this.y = Math.min( this.y, v.y );
  453. return this;
  454. },
  455. max: function ( v ) {
  456. this.x = Math.max( this.x, v.x );
  457. this.y = Math.max( this.y, v.y );
  458. return this;
  459. },
  460. clamp: function ( min, max ) {
  461. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  462. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  463. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  464. return this;
  465. },
  466. clampScalar: function () {
  467. var min, max;
  468. return function clampScalar( minVal, maxVal ) {
  469. if ( min === undefined ) {
  470. min = new Vector2();
  471. max = new Vector2();
  472. }
  473. min.set( minVal, minVal );
  474. max.set( maxVal, maxVal );
  475. return this.clamp( min, max );
  476. };
  477. }(),
  478. clampLength: function ( min, max ) {
  479. var length = this.length();
  480. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  481. },
  482. floor: function () {
  483. this.x = Math.floor( this.x );
  484. this.y = Math.floor( this.y );
  485. return this;
  486. },
  487. ceil: function () {
  488. this.x = Math.ceil( this.x );
  489. this.y = Math.ceil( this.y );
  490. return this;
  491. },
  492. round: function () {
  493. this.x = Math.round( this.x );
  494. this.y = Math.round( this.y );
  495. return this;
  496. },
  497. roundToZero: function () {
  498. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  499. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  500. return this;
  501. },
  502. negate: function () {
  503. this.x = - this.x;
  504. this.y = - this.y;
  505. return this;
  506. },
  507. dot: function ( v ) {
  508. return this.x * v.x + this.y * v.y;
  509. },
  510. lengthSq: function () {
  511. return this.x * this.x + this.y * this.y;
  512. },
  513. length: function () {
  514. return Math.sqrt( this.x * this.x + this.y * this.y );
  515. },
  516. lengthManhattan: function() {
  517. return Math.abs( this.x ) + Math.abs( this.y );
  518. },
  519. normalize: function () {
  520. return this.divideScalar( this.length() );
  521. },
  522. angle: function () {
  523. // computes the angle in radians with respect to the positive x-axis
  524. var angle = Math.atan2( this.y, this.x );
  525. if ( angle < 0 ) angle += 2 * Math.PI;
  526. return angle;
  527. },
  528. distanceTo: function ( v ) {
  529. return Math.sqrt( this.distanceToSquared( v ) );
  530. },
  531. distanceToSquared: function ( v ) {
  532. var dx = this.x - v.x, dy = this.y - v.y;
  533. return dx * dx + dy * dy;
  534. },
  535. distanceToManhattan: function ( v ) {
  536. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  537. },
  538. setLength: function ( length ) {
  539. return this.multiplyScalar( length / this.length() );
  540. },
  541. lerp: function ( v, alpha ) {
  542. this.x += ( v.x - this.x ) * alpha;
  543. this.y += ( v.y - this.y ) * alpha;
  544. return this;
  545. },
  546. lerpVectors: function ( v1, v2, alpha ) {
  547. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  548. },
  549. equals: function ( v ) {
  550. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  551. },
  552. fromArray: function ( array, offset ) {
  553. if ( offset === undefined ) offset = 0;
  554. this.x = array[ offset ];
  555. this.y = array[ offset + 1 ];
  556. return this;
  557. },
  558. toArray: function ( array, offset ) {
  559. if ( array === undefined ) array = [];
  560. if ( offset === undefined ) offset = 0;
  561. array[ offset ] = this.x;
  562. array[ offset + 1 ] = this.y;
  563. return array;
  564. },
  565. fromAttribute: function ( attribute, index, offset ) {
  566. if ( offset === undefined ) offset = 0;
  567. index = index * attribute.itemSize + offset;
  568. this.x = attribute.array[ index ];
  569. this.y = attribute.array[ index + 1 ];
  570. return this;
  571. },
  572. rotateAround: function ( center, angle ) {
  573. var c = Math.cos( angle ), s = Math.sin( angle );
  574. var x = this.x - center.x;
  575. var y = this.y - center.y;
  576. this.x = x * c - y * s + center.x;
  577. this.y = x * s + y * c + center.y;
  578. return this;
  579. }
  580. };
  581. /**
  582. * @author mrdoob / http://mrdoob.com/
  583. * @author alteredq / http://alteredqualia.com/
  584. * @author szimek / https://github.com/szimek/
  585. */
  586. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  587. Object.defineProperty( this, 'id', { value: TextureIdCount() } );
  588. this.uuid = exports.Math.generateUUID();
  589. this.name = '';
  590. this.sourceFile = '';
  591. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  592. this.mipmaps = [];
  593. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  594. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  595. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  596. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  597. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  598. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  599. this.format = format !== undefined ? format : RGBAFormat;
  600. this.type = type !== undefined ? type : UnsignedByteType;
  601. this.offset = new Vector2( 0, 0 );
  602. this.repeat = new Vector2( 1, 1 );
  603. this.generateMipmaps = true;
  604. this.premultiplyAlpha = false;
  605. this.flipY = true;
  606. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  607. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  608. //
  609. // Also changing the encoding after already used by a Material will not automatically make the Material
  610. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  611. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  612. this.version = 0;
  613. this.onUpdate = null;
  614. }
  615. Texture.DEFAULT_IMAGE = undefined;
  616. Texture.DEFAULT_MAPPING = UVMapping;
  617. Texture.prototype = {
  618. constructor: Texture,
  619. isTexture: true,
  620. set needsUpdate( value ) {
  621. if ( value === true ) this.version ++;
  622. },
  623. clone: function () {
  624. return new this.constructor().copy( this );
  625. },
  626. copy: function ( source ) {
  627. this.image = source.image;
  628. this.mipmaps = source.mipmaps.slice( 0 );
  629. this.mapping = source.mapping;
  630. this.wrapS = source.wrapS;
  631. this.wrapT = source.wrapT;
  632. this.magFilter = source.magFilter;
  633. this.minFilter = source.minFilter;
  634. this.anisotropy = source.anisotropy;
  635. this.format = source.format;
  636. this.type = source.type;
  637. this.offset.copy( source.offset );
  638. this.repeat.copy( source.repeat );
  639. this.generateMipmaps = source.generateMipmaps;
  640. this.premultiplyAlpha = source.premultiplyAlpha;
  641. this.flipY = source.flipY;
  642. this.unpackAlignment = source.unpackAlignment;
  643. this.encoding = source.encoding;
  644. return this;
  645. },
  646. toJSON: function ( meta ) {
  647. if ( meta.textures[ this.uuid ] !== undefined ) {
  648. return meta.textures[ this.uuid ];
  649. }
  650. function getDataURL( image ) {
  651. var canvas;
  652. if ( image.toDataURL !== undefined ) {
  653. canvas = image;
  654. } else {
  655. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  656. canvas.width = image.width;
  657. canvas.height = image.height;
  658. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  659. }
  660. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  661. return canvas.toDataURL( 'image/jpeg', 0.6 );
  662. } else {
  663. return canvas.toDataURL( 'image/png' );
  664. }
  665. }
  666. var output = {
  667. metadata: {
  668. version: 4.4,
  669. type: 'Texture',
  670. generator: 'Texture.toJSON'
  671. },
  672. uuid: this.uuid,
  673. name: this.name,
  674. mapping: this.mapping,
  675. repeat: [ this.repeat.x, this.repeat.y ],
  676. offset: [ this.offset.x, this.offset.y ],
  677. wrap: [ this.wrapS, this.wrapT ],
  678. minFilter: this.minFilter,
  679. magFilter: this.magFilter,
  680. anisotropy: this.anisotropy,
  681. flipY: this.flipY
  682. };
  683. if ( this.image !== undefined ) {
  684. // TODO: Move to THREE.Image
  685. var image = this.image;
  686. if ( image.uuid === undefined ) {
  687. image.uuid = exports.Math.generateUUID(); // UGH
  688. }
  689. if ( meta.images[ image.uuid ] === undefined ) {
  690. meta.images[ image.uuid ] = {
  691. uuid: image.uuid,
  692. url: getDataURL( image )
  693. };
  694. }
  695. output.image = image.uuid;
  696. }
  697. meta.textures[ this.uuid ] = output;
  698. return output;
  699. },
  700. dispose: function () {
  701. this.dispatchEvent( { type: 'dispose' } );
  702. },
  703. transformUv: function ( uv ) {
  704. if ( this.mapping !== UVMapping ) return;
  705. uv.multiply( this.repeat );
  706. uv.add( this.offset );
  707. if ( uv.x < 0 || uv.x > 1 ) {
  708. switch ( this.wrapS ) {
  709. case RepeatWrapping:
  710. uv.x = uv.x - Math.floor( uv.x );
  711. break;
  712. case ClampToEdgeWrapping:
  713. uv.x = uv.x < 0 ? 0 : 1;
  714. break;
  715. case MirroredRepeatWrapping:
  716. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  717. uv.x = Math.ceil( uv.x ) - uv.x;
  718. } else {
  719. uv.x = uv.x - Math.floor( uv.x );
  720. }
  721. break;
  722. }
  723. }
  724. if ( uv.y < 0 || uv.y > 1 ) {
  725. switch ( this.wrapT ) {
  726. case RepeatWrapping:
  727. uv.y = uv.y - Math.floor( uv.y );
  728. break;
  729. case ClampToEdgeWrapping:
  730. uv.y = uv.y < 0 ? 0 : 1;
  731. break;
  732. case MirroredRepeatWrapping:
  733. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  734. uv.y = Math.ceil( uv.y ) - uv.y;
  735. } else {
  736. uv.y = uv.y - Math.floor( uv.y );
  737. }
  738. break;
  739. }
  740. }
  741. if ( this.flipY ) {
  742. uv.y = 1 - uv.y;
  743. }
  744. }
  745. };
  746. Object.assign( Texture.prototype, EventDispatcher.prototype );
  747. var count = 0;
  748. function TextureIdCount() { return count++; };
  749. /**
  750. * @author supereggbert / http://www.paulbrunt.co.uk/
  751. * @author philogb / http://blog.thejit.org/
  752. * @author mikael emtinger / http://gomo.se/
  753. * @author egraether / http://egraether.com/
  754. * @author WestLangley / http://github.com/WestLangley
  755. */
  756. function Vector4( x, y, z, w ) {
  757. this.x = x || 0;
  758. this.y = y || 0;
  759. this.z = z || 0;
  760. this.w = ( w !== undefined ) ? w : 1;
  761. }
  762. Vector4.prototype = {
  763. constructor: Vector4,
  764. isVector4: true,
  765. set: function ( x, y, z, w ) {
  766. this.x = x;
  767. this.y = y;
  768. this.z = z;
  769. this.w = w;
  770. return this;
  771. },
  772. setScalar: function ( scalar ) {
  773. this.x = scalar;
  774. this.y = scalar;
  775. this.z = scalar;
  776. this.w = scalar;
  777. return this;
  778. },
  779. setX: function ( x ) {
  780. this.x = x;
  781. return this;
  782. },
  783. setY: function ( y ) {
  784. this.y = y;
  785. return this;
  786. },
  787. setZ: function ( z ) {
  788. this.z = z;
  789. return this;
  790. },
  791. setW: function ( w ) {
  792. this.w = w;
  793. return this;
  794. },
  795. setComponent: function ( index, value ) {
  796. switch ( index ) {
  797. case 0: this.x = value; break;
  798. case 1: this.y = value; break;
  799. case 2: this.z = value; break;
  800. case 3: this.w = value; break;
  801. default: throw new Error( 'index is out of range: ' + index );
  802. }
  803. },
  804. getComponent: function ( index ) {
  805. switch ( index ) {
  806. case 0: return this.x;
  807. case 1: return this.y;
  808. case 2: return this.z;
  809. case 3: return this.w;
  810. default: throw new Error( 'index is out of range: ' + index );
  811. }
  812. },
  813. clone: function () {
  814. return new this.constructor( this.x, this.y, this.z, this.w );
  815. },
  816. copy: function ( v ) {
  817. this.x = v.x;
  818. this.y = v.y;
  819. this.z = v.z;
  820. this.w = ( v.w !== undefined ) ? v.w : 1;
  821. return this;
  822. },
  823. add: function ( v, w ) {
  824. if ( w !== undefined ) {
  825. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  826. return this.addVectors( v, w );
  827. }
  828. this.x += v.x;
  829. this.y += v.y;
  830. this.z += v.z;
  831. this.w += v.w;
  832. return this;
  833. },
  834. addScalar: function ( s ) {
  835. this.x += s;
  836. this.y += s;
  837. this.z += s;
  838. this.w += s;
  839. return this;
  840. },
  841. addVectors: function ( a, b ) {
  842. this.x = a.x + b.x;
  843. this.y = a.y + b.y;
  844. this.z = a.z + b.z;
  845. this.w = a.w + b.w;
  846. return this;
  847. },
  848. addScaledVector: function ( v, s ) {
  849. this.x += v.x * s;
  850. this.y += v.y * s;
  851. this.z += v.z * s;
  852. this.w += v.w * s;
  853. return this;
  854. },
  855. sub: function ( v, w ) {
  856. if ( w !== undefined ) {
  857. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  858. return this.subVectors( v, w );
  859. }
  860. this.x -= v.x;
  861. this.y -= v.y;
  862. this.z -= v.z;
  863. this.w -= v.w;
  864. return this;
  865. },
  866. subScalar: function ( s ) {
  867. this.x -= s;
  868. this.y -= s;
  869. this.z -= s;
  870. this.w -= s;
  871. return this;
  872. },
  873. subVectors: function ( a, b ) {
  874. this.x = a.x - b.x;
  875. this.y = a.y - b.y;
  876. this.z = a.z - b.z;
  877. this.w = a.w - b.w;
  878. return this;
  879. },
  880. multiplyScalar: function ( scalar ) {
  881. if ( isFinite( scalar ) ) {
  882. this.x *= scalar;
  883. this.y *= scalar;
  884. this.z *= scalar;
  885. this.w *= scalar;
  886. } else {
  887. this.x = 0;
  888. this.y = 0;
  889. this.z = 0;
  890. this.w = 0;
  891. }
  892. return this;
  893. },
  894. applyMatrix4: function ( m ) {
  895. var x = this.x, y = this.y, z = this.z, w = this.w;
  896. var e = m.elements;
  897. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  898. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  899. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  900. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  901. return this;
  902. },
  903. divideScalar: function ( scalar ) {
  904. return this.multiplyScalar( 1 / scalar );
  905. },
  906. setAxisAngleFromQuaternion: function ( q ) {
  907. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  908. // q is assumed to be normalized
  909. this.w = 2 * Math.acos( q.w );
  910. var s = Math.sqrt( 1 - q.w * q.w );
  911. if ( s < 0.0001 ) {
  912. this.x = 1;
  913. this.y = 0;
  914. this.z = 0;
  915. } else {
  916. this.x = q.x / s;
  917. this.y = q.y / s;
  918. this.z = q.z / s;
  919. }
  920. return this;
  921. },
  922. setAxisAngleFromRotationMatrix: function ( m ) {
  923. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  924. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  925. var angle, x, y, z, // variables for result
  926. epsilon = 0.01, // margin to allow for rounding errors
  927. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  928. te = m.elements,
  929. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  930. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  931. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  932. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  933. ( Math.abs( m13 - m31 ) < epsilon ) &&
  934. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  935. // singularity found
  936. // first check for identity matrix which must have +1 for all terms
  937. // in leading diagonal and zero in other terms
  938. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  939. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  940. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  941. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  942. // this singularity is identity matrix so angle = 0
  943. this.set( 1, 0, 0, 0 );
  944. return this; // zero angle, arbitrary axis
  945. }
  946. // otherwise this singularity is angle = 180
  947. angle = Math.PI;
  948. var xx = ( m11 + 1 ) / 2;
  949. var yy = ( m22 + 1 ) / 2;
  950. var zz = ( m33 + 1 ) / 2;
  951. var xy = ( m12 + m21 ) / 4;
  952. var xz = ( m13 + m31 ) / 4;
  953. var yz = ( m23 + m32 ) / 4;
  954. if ( ( xx > yy ) && ( xx > zz ) ) {
  955. // m11 is the largest diagonal term
  956. if ( xx < epsilon ) {
  957. x = 0;
  958. y = 0.707106781;
  959. z = 0.707106781;
  960. } else {
  961. x = Math.sqrt( xx );
  962. y = xy / x;
  963. z = xz / x;
  964. }
  965. } else if ( yy > zz ) {
  966. // m22 is the largest diagonal term
  967. if ( yy < epsilon ) {
  968. x = 0.707106781;
  969. y = 0;
  970. z = 0.707106781;
  971. } else {
  972. y = Math.sqrt( yy );
  973. x = xy / y;
  974. z = yz / y;
  975. }
  976. } else {
  977. // m33 is the largest diagonal term so base result on this
  978. if ( zz < epsilon ) {
  979. x = 0.707106781;
  980. y = 0.707106781;
  981. z = 0;
  982. } else {
  983. z = Math.sqrt( zz );
  984. x = xz / z;
  985. y = yz / z;
  986. }
  987. }
  988. this.set( x, y, z, angle );
  989. return this; // return 180 deg rotation
  990. }
  991. // as we have reached here there are no singularities so we can handle normally
  992. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  993. ( m13 - m31 ) * ( m13 - m31 ) +
  994. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  995. if ( Math.abs( s ) < 0.001 ) s = 1;
  996. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  997. // caught by singularity test above, but I've left it in just in case
  998. this.x = ( m32 - m23 ) / s;
  999. this.y = ( m13 - m31 ) / s;
  1000. this.z = ( m21 - m12 ) / s;
  1001. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1002. return this;
  1003. },
  1004. min: function ( v ) {
  1005. this.x = Math.min( this.x, v.x );
  1006. this.y = Math.min( this.y, v.y );
  1007. this.z = Math.min( this.z, v.z );
  1008. this.w = Math.min( this.w, v.w );
  1009. return this;
  1010. },
  1011. max: function ( v ) {
  1012. this.x = Math.max( this.x, v.x );
  1013. this.y = Math.max( this.y, v.y );
  1014. this.z = Math.max( this.z, v.z );
  1015. this.w = Math.max( this.w, v.w );
  1016. return this;
  1017. },
  1018. clamp: function ( min, max ) {
  1019. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1020. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1021. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1022. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1023. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1024. return this;
  1025. },
  1026. clampScalar: function () {
  1027. var min, max;
  1028. return function clampScalar( minVal, maxVal ) {
  1029. if ( min === undefined ) {
  1030. min = new Vector4();
  1031. max = new Vector4();
  1032. }
  1033. min.set( minVal, minVal, minVal, minVal );
  1034. max.set( maxVal, maxVal, maxVal, maxVal );
  1035. return this.clamp( min, max );
  1036. };
  1037. }(),
  1038. floor: function () {
  1039. this.x = Math.floor( this.x );
  1040. this.y = Math.floor( this.y );
  1041. this.z = Math.floor( this.z );
  1042. this.w = Math.floor( this.w );
  1043. return this;
  1044. },
  1045. ceil: function () {
  1046. this.x = Math.ceil( this.x );
  1047. this.y = Math.ceil( this.y );
  1048. this.z = Math.ceil( this.z );
  1049. this.w = Math.ceil( this.w );
  1050. return this;
  1051. },
  1052. round: function () {
  1053. this.x = Math.round( this.x );
  1054. this.y = Math.round( this.y );
  1055. this.z = Math.round( this.z );
  1056. this.w = Math.round( this.w );
  1057. return this;
  1058. },
  1059. roundToZero: function () {
  1060. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1061. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1062. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1063. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1064. return this;
  1065. },
  1066. negate: function () {
  1067. this.x = - this.x;
  1068. this.y = - this.y;
  1069. this.z = - this.z;
  1070. this.w = - this.w;
  1071. return this;
  1072. },
  1073. dot: function ( v ) {
  1074. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1075. },
  1076. lengthSq: function () {
  1077. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1078. },
  1079. length: function () {
  1080. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1081. },
  1082. lengthManhattan: function () {
  1083. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1084. },
  1085. normalize: function () {
  1086. return this.divideScalar( this.length() );
  1087. },
  1088. setLength: function ( length ) {
  1089. return this.multiplyScalar( length / this.length() );
  1090. },
  1091. lerp: function ( v, alpha ) {
  1092. this.x += ( v.x - this.x ) * alpha;
  1093. this.y += ( v.y - this.y ) * alpha;
  1094. this.z += ( v.z - this.z ) * alpha;
  1095. this.w += ( v.w - this.w ) * alpha;
  1096. return this;
  1097. },
  1098. lerpVectors: function ( v1, v2, alpha ) {
  1099. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1100. },
  1101. equals: function ( v ) {
  1102. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1103. },
  1104. fromArray: function ( array, offset ) {
  1105. if ( offset === undefined ) offset = 0;
  1106. this.x = array[ offset ];
  1107. this.y = array[ offset + 1 ];
  1108. this.z = array[ offset + 2 ];
  1109. this.w = array[ offset + 3 ];
  1110. return this;
  1111. },
  1112. toArray: function ( array, offset ) {
  1113. if ( array === undefined ) array = [];
  1114. if ( offset === undefined ) offset = 0;
  1115. array[ offset ] = this.x;
  1116. array[ offset + 1 ] = this.y;
  1117. array[ offset + 2 ] = this.z;
  1118. array[ offset + 3 ] = this.w;
  1119. return array;
  1120. },
  1121. fromAttribute: function ( attribute, index, offset ) {
  1122. if ( offset === undefined ) offset = 0;
  1123. index = index * attribute.itemSize + offset;
  1124. this.x = attribute.array[ index ];
  1125. this.y = attribute.array[ index + 1 ];
  1126. this.z = attribute.array[ index + 2 ];
  1127. this.w = attribute.array[ index + 3 ];
  1128. return this;
  1129. }
  1130. };
  1131. /**
  1132. * @author szimek / https://github.com/szimek/
  1133. * @author alteredq / http://alteredqualia.com/
  1134. * @author Marius Kintel / https://github.com/kintel
  1135. */
  1136. /*
  1137. In options, we can specify:
  1138. * Texture parameters for an auto-generated target texture
  1139. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1140. */
  1141. function WebGLRenderTarget( width, height, options ) {
  1142. this.uuid = exports.Math.generateUUID();
  1143. this.width = width;
  1144. this.height = height;
  1145. this.scissor = new Vector4( 0, 0, width, height );
  1146. this.scissorTest = false;
  1147. this.viewport = new Vector4( 0, 0, width, height );
  1148. options = options || {};
  1149. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1150. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1151. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1152. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1153. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1154. }
  1155. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1156. isWebGLRenderTarget: true,
  1157. setSize: function ( width, height ) {
  1158. if ( this.width !== width || this.height !== height ) {
  1159. this.width = width;
  1160. this.height = height;
  1161. this.dispose();
  1162. }
  1163. this.viewport.set( 0, 0, width, height );
  1164. this.scissor.set( 0, 0, width, height );
  1165. },
  1166. clone: function () {
  1167. return new this.constructor().copy( this );
  1168. },
  1169. copy: function ( source ) {
  1170. this.width = source.width;
  1171. this.height = source.height;
  1172. this.viewport.copy( source.viewport );
  1173. this.texture = source.texture.clone();
  1174. this.depthBuffer = source.depthBuffer;
  1175. this.stencilBuffer = source.stencilBuffer;
  1176. this.depthTexture = source.depthTexture;
  1177. return this;
  1178. },
  1179. dispose: function () {
  1180. this.dispatchEvent( { type: 'dispose' } );
  1181. }
  1182. } );
  1183. /**
  1184. * @author alteredq / http://alteredqualia.com
  1185. */
  1186. function WebGLRenderTargetCube( width, height, options ) {
  1187. WebGLRenderTarget.call( this, width, height, options );
  1188. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1189. this.activeMipMapLevel = 0;
  1190. }
  1191. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1192. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1193. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1194. /**
  1195. * @author mikael emtinger / http://gomo.se/
  1196. * @author alteredq / http://alteredqualia.com/
  1197. * @author WestLangley / http://github.com/WestLangley
  1198. * @author bhouston / http://clara.io
  1199. */
  1200. function Quaternion( x, y, z, w ) {
  1201. this._x = x || 0;
  1202. this._y = y || 0;
  1203. this._z = z || 0;
  1204. this._w = ( w !== undefined ) ? w : 1;
  1205. }
  1206. Quaternion.prototype = {
  1207. constructor: Quaternion,
  1208. get x () {
  1209. return this._x;
  1210. },
  1211. set x ( value ) {
  1212. this._x = value;
  1213. this.onChangeCallback();
  1214. },
  1215. get y () {
  1216. return this._y;
  1217. },
  1218. set y ( value ) {
  1219. this._y = value;
  1220. this.onChangeCallback();
  1221. },
  1222. get z () {
  1223. return this._z;
  1224. },
  1225. set z ( value ) {
  1226. this._z = value;
  1227. this.onChangeCallback();
  1228. },
  1229. get w () {
  1230. return this._w;
  1231. },
  1232. set w ( value ) {
  1233. this._w = value;
  1234. this.onChangeCallback();
  1235. },
  1236. set: function ( x, y, z, w ) {
  1237. this._x = x;
  1238. this._y = y;
  1239. this._z = z;
  1240. this._w = w;
  1241. this.onChangeCallback();
  1242. return this;
  1243. },
  1244. clone: function () {
  1245. return new this.constructor( this._x, this._y, this._z, this._w );
  1246. },
  1247. copy: function ( quaternion ) {
  1248. this._x = quaternion.x;
  1249. this._y = quaternion.y;
  1250. this._z = quaternion.z;
  1251. this._w = quaternion.w;
  1252. this.onChangeCallback();
  1253. return this;
  1254. },
  1255. setFromEuler: function ( euler, update ) {
  1256. if ( (euler && euler.isEuler) === false ) {
  1257. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1258. }
  1259. // http://www.mathworks.com/matlabcentral/fileexchange/
  1260. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1261. // content/SpinCalc.m
  1262. var c1 = Math.cos( euler._x / 2 );
  1263. var c2 = Math.cos( euler._y / 2 );
  1264. var c3 = Math.cos( euler._z / 2 );
  1265. var s1 = Math.sin( euler._x / 2 );
  1266. var s2 = Math.sin( euler._y / 2 );
  1267. var s3 = Math.sin( euler._z / 2 );
  1268. var order = euler.order;
  1269. if ( order === 'XYZ' ) {
  1270. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1271. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1272. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1273. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1274. } else if ( order === 'YXZ' ) {
  1275. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1276. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1277. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1278. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1279. } else if ( order === 'ZXY' ) {
  1280. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1281. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1282. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1283. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1284. } else if ( order === 'ZYX' ) {
  1285. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1286. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1287. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1288. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1289. } else if ( order === 'YZX' ) {
  1290. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1291. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1292. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1293. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1294. } else if ( order === 'XZY' ) {
  1295. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1296. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1297. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1298. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1299. }
  1300. if ( update !== false ) this.onChangeCallback();
  1301. return this;
  1302. },
  1303. setFromAxisAngle: function ( axis, angle ) {
  1304. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1305. // assumes axis is normalized
  1306. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1307. this._x = axis.x * s;
  1308. this._y = axis.y * s;
  1309. this._z = axis.z * s;
  1310. this._w = Math.cos( halfAngle );
  1311. this.onChangeCallback();
  1312. return this;
  1313. },
  1314. setFromRotationMatrix: function ( m ) {
  1315. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1316. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1317. var te = m.elements,
  1318. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1319. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1320. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1321. trace = m11 + m22 + m33,
  1322. s;
  1323. if ( trace > 0 ) {
  1324. s = 0.5 / Math.sqrt( trace + 1.0 );
  1325. this._w = 0.25 / s;
  1326. this._x = ( m32 - m23 ) * s;
  1327. this._y = ( m13 - m31 ) * s;
  1328. this._z = ( m21 - m12 ) * s;
  1329. } else if ( m11 > m22 && m11 > m33 ) {
  1330. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1331. this._w = ( m32 - m23 ) / s;
  1332. this._x = 0.25 * s;
  1333. this._y = ( m12 + m21 ) / s;
  1334. this._z = ( m13 + m31 ) / s;
  1335. } else if ( m22 > m33 ) {
  1336. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1337. this._w = ( m13 - m31 ) / s;
  1338. this._x = ( m12 + m21 ) / s;
  1339. this._y = 0.25 * s;
  1340. this._z = ( m23 + m32 ) / s;
  1341. } else {
  1342. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1343. this._w = ( m21 - m12 ) / s;
  1344. this._x = ( m13 + m31 ) / s;
  1345. this._y = ( m23 + m32 ) / s;
  1346. this._z = 0.25 * s;
  1347. }
  1348. this.onChangeCallback();
  1349. return this;
  1350. },
  1351. setFromUnitVectors: function () {
  1352. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1353. // assumes direction vectors vFrom and vTo are normalized
  1354. var v1, r;
  1355. var EPS = 0.000001;
  1356. return function setFromUnitVectors( vFrom, vTo ) {
  1357. if ( v1 === undefined ) v1 = new Vector3();
  1358. r = vFrom.dot( vTo ) + 1;
  1359. if ( r < EPS ) {
  1360. r = 0;
  1361. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1362. v1.set( - vFrom.y, vFrom.x, 0 );
  1363. } else {
  1364. v1.set( 0, - vFrom.z, vFrom.y );
  1365. }
  1366. } else {
  1367. v1.crossVectors( vFrom, vTo );
  1368. }
  1369. this._x = v1.x;
  1370. this._y = v1.y;
  1371. this._z = v1.z;
  1372. this._w = r;
  1373. return this.normalize();
  1374. };
  1375. }(),
  1376. inverse: function () {
  1377. return this.conjugate().normalize();
  1378. },
  1379. conjugate: function () {
  1380. this._x *= - 1;
  1381. this._y *= - 1;
  1382. this._z *= - 1;
  1383. this.onChangeCallback();
  1384. return this;
  1385. },
  1386. dot: function ( v ) {
  1387. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1388. },
  1389. lengthSq: function () {
  1390. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1391. },
  1392. length: function () {
  1393. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1394. },
  1395. normalize: function () {
  1396. var l = this.length();
  1397. if ( l === 0 ) {
  1398. this._x = 0;
  1399. this._y = 0;
  1400. this._z = 0;
  1401. this._w = 1;
  1402. } else {
  1403. l = 1 / l;
  1404. this._x = this._x * l;
  1405. this._y = this._y * l;
  1406. this._z = this._z * l;
  1407. this._w = this._w * l;
  1408. }
  1409. this.onChangeCallback();
  1410. return this;
  1411. },
  1412. multiply: function ( q, p ) {
  1413. if ( p !== undefined ) {
  1414. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1415. return this.multiplyQuaternions( q, p );
  1416. }
  1417. return this.multiplyQuaternions( this, q );
  1418. },
  1419. premultiply: function ( q ) {
  1420. return this.multiplyQuaternions( q, this );
  1421. },
  1422. multiplyQuaternions: function ( a, b ) {
  1423. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1424. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1425. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1426. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1427. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1428. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1429. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1430. this.onChangeCallback();
  1431. return this;
  1432. },
  1433. slerp: function ( qb, t ) {
  1434. if ( t === 0 ) return this;
  1435. if ( t === 1 ) return this.copy( qb );
  1436. var x = this._x, y = this._y, z = this._z, w = this._w;
  1437. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1438. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1439. if ( cosHalfTheta < 0 ) {
  1440. this._w = - qb._w;
  1441. this._x = - qb._x;
  1442. this._y = - qb._y;
  1443. this._z = - qb._z;
  1444. cosHalfTheta = - cosHalfTheta;
  1445. } else {
  1446. this.copy( qb );
  1447. }
  1448. if ( cosHalfTheta >= 1.0 ) {
  1449. this._w = w;
  1450. this._x = x;
  1451. this._y = y;
  1452. this._z = z;
  1453. return this;
  1454. }
  1455. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1456. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1457. this._w = 0.5 * ( w + this._w );
  1458. this._x = 0.5 * ( x + this._x );
  1459. this._y = 0.5 * ( y + this._y );
  1460. this._z = 0.5 * ( z + this._z );
  1461. return this;
  1462. }
  1463. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1464. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1465. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1466. this._w = ( w * ratioA + this._w * ratioB );
  1467. this._x = ( x * ratioA + this._x * ratioB );
  1468. this._y = ( y * ratioA + this._y * ratioB );
  1469. this._z = ( z * ratioA + this._z * ratioB );
  1470. this.onChangeCallback();
  1471. return this;
  1472. },
  1473. equals: function ( quaternion ) {
  1474. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1475. },
  1476. fromArray: function ( array, offset ) {
  1477. if ( offset === undefined ) offset = 0;
  1478. this._x = array[ offset ];
  1479. this._y = array[ offset + 1 ];
  1480. this._z = array[ offset + 2 ];
  1481. this._w = array[ offset + 3 ];
  1482. this.onChangeCallback();
  1483. return this;
  1484. },
  1485. toArray: function ( array, offset ) {
  1486. if ( array === undefined ) array = [];
  1487. if ( offset === undefined ) offset = 0;
  1488. array[ offset ] = this._x;
  1489. array[ offset + 1 ] = this._y;
  1490. array[ offset + 2 ] = this._z;
  1491. array[ offset + 3 ] = this._w;
  1492. return array;
  1493. },
  1494. onChange: function ( callback ) {
  1495. this.onChangeCallback = callback;
  1496. return this;
  1497. },
  1498. onChangeCallback: function () {}
  1499. };
  1500. Object.assign( Quaternion, {
  1501. slerp: function( qa, qb, qm, t ) {
  1502. return qm.copy( qa ).slerp( qb, t );
  1503. },
  1504. slerpFlat: function(
  1505. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1506. // fuzz-free, array-based Quaternion SLERP operation
  1507. var x0 = src0[ srcOffset0 + 0 ],
  1508. y0 = src0[ srcOffset0 + 1 ],
  1509. z0 = src0[ srcOffset0 + 2 ],
  1510. w0 = src0[ srcOffset0 + 3 ],
  1511. x1 = src1[ srcOffset1 + 0 ],
  1512. y1 = src1[ srcOffset1 + 1 ],
  1513. z1 = src1[ srcOffset1 + 2 ],
  1514. w1 = src1[ srcOffset1 + 3 ];
  1515. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1516. var s = 1 - t,
  1517. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1518. dir = ( cos >= 0 ? 1 : - 1 ),
  1519. sqrSin = 1 - cos * cos;
  1520. // Skip the Slerp for tiny steps to avoid numeric problems:
  1521. if ( sqrSin > Number.EPSILON ) {
  1522. var sin = Math.sqrt( sqrSin ),
  1523. len = Math.atan2( sin, cos * dir );
  1524. s = Math.sin( s * len ) / sin;
  1525. t = Math.sin( t * len ) / sin;
  1526. }
  1527. var tDir = t * dir;
  1528. x0 = x0 * s + x1 * tDir;
  1529. y0 = y0 * s + y1 * tDir;
  1530. z0 = z0 * s + z1 * tDir;
  1531. w0 = w0 * s + w1 * tDir;
  1532. // Normalize in case we just did a lerp:
  1533. if ( s === 1 - t ) {
  1534. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1535. x0 *= f;
  1536. y0 *= f;
  1537. z0 *= f;
  1538. w0 *= f;
  1539. }
  1540. }
  1541. dst[ dstOffset ] = x0;
  1542. dst[ dstOffset + 1 ] = y0;
  1543. dst[ dstOffset + 2 ] = z0;
  1544. dst[ dstOffset + 3 ] = w0;
  1545. }
  1546. } );
  1547. /**
  1548. * @author mrdoob / http://mrdoob.com/
  1549. * @author *kile / http://kile.stravaganza.org/
  1550. * @author philogb / http://blog.thejit.org/
  1551. * @author mikael emtinger / http://gomo.se/
  1552. * @author egraether / http://egraether.com/
  1553. * @author WestLangley / http://github.com/WestLangley
  1554. */
  1555. function Vector3( x, y, z ) {
  1556. this.x = x || 0;
  1557. this.y = y || 0;
  1558. this.z = z || 0;
  1559. }
  1560. Vector3.prototype = {
  1561. constructor: Vector3,
  1562. isVector3: true,
  1563. set: function ( x, y, z ) {
  1564. this.x = x;
  1565. this.y = y;
  1566. this.z = z;
  1567. return this;
  1568. },
  1569. setScalar: function ( scalar ) {
  1570. this.x = scalar;
  1571. this.y = scalar;
  1572. this.z = scalar;
  1573. return this;
  1574. },
  1575. setX: function ( x ) {
  1576. this.x = x;
  1577. return this;
  1578. },
  1579. setY: function ( y ) {
  1580. this.y = y;
  1581. return this;
  1582. },
  1583. setZ: function ( z ) {
  1584. this.z = z;
  1585. return this;
  1586. },
  1587. setComponent: function ( index, value ) {
  1588. switch ( index ) {
  1589. case 0: this.x = value; break;
  1590. case 1: this.y = value; break;
  1591. case 2: this.z = value; break;
  1592. default: throw new Error( 'index is out of range: ' + index );
  1593. }
  1594. },
  1595. getComponent: function ( index ) {
  1596. switch ( index ) {
  1597. case 0: return this.x;
  1598. case 1: return this.y;
  1599. case 2: return this.z;
  1600. default: throw new Error( 'index is out of range: ' + index );
  1601. }
  1602. },
  1603. clone: function () {
  1604. return new this.constructor( this.x, this.y, this.z );
  1605. },
  1606. copy: function ( v ) {
  1607. this.x = v.x;
  1608. this.y = v.y;
  1609. this.z = v.z;
  1610. return this;
  1611. },
  1612. add: function ( v, w ) {
  1613. if ( w !== undefined ) {
  1614. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1615. return this.addVectors( v, w );
  1616. }
  1617. this.x += v.x;
  1618. this.y += v.y;
  1619. this.z += v.z;
  1620. return this;
  1621. },
  1622. addScalar: function ( s ) {
  1623. this.x += s;
  1624. this.y += s;
  1625. this.z += s;
  1626. return this;
  1627. },
  1628. addVectors: function ( a, b ) {
  1629. this.x = a.x + b.x;
  1630. this.y = a.y + b.y;
  1631. this.z = a.z + b.z;
  1632. return this;
  1633. },
  1634. addScaledVector: function ( v, s ) {
  1635. this.x += v.x * s;
  1636. this.y += v.y * s;
  1637. this.z += v.z * s;
  1638. return this;
  1639. },
  1640. sub: function ( v, w ) {
  1641. if ( w !== undefined ) {
  1642. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1643. return this.subVectors( v, w );
  1644. }
  1645. this.x -= v.x;
  1646. this.y -= v.y;
  1647. this.z -= v.z;
  1648. return this;
  1649. },
  1650. subScalar: function ( s ) {
  1651. this.x -= s;
  1652. this.y -= s;
  1653. this.z -= s;
  1654. return this;
  1655. },
  1656. subVectors: 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. return this;
  1661. },
  1662. multiply: function ( v, w ) {
  1663. if ( w !== undefined ) {
  1664. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1665. return this.multiplyVectors( v, w );
  1666. }
  1667. this.x *= v.x;
  1668. this.y *= v.y;
  1669. this.z *= v.z;
  1670. return this;
  1671. },
  1672. multiplyScalar: function ( scalar ) {
  1673. if ( isFinite( scalar ) ) {
  1674. this.x *= scalar;
  1675. this.y *= scalar;
  1676. this.z *= scalar;
  1677. } else {
  1678. this.x = 0;
  1679. this.y = 0;
  1680. this.z = 0;
  1681. }
  1682. return this;
  1683. },
  1684. multiplyVectors: function ( a, b ) {
  1685. this.x = a.x * b.x;
  1686. this.y = a.y * b.y;
  1687. this.z = a.z * b.z;
  1688. return this;
  1689. },
  1690. applyEuler: function () {
  1691. var quaternion;
  1692. return function applyEuler( euler ) {
  1693. if ( (euler && euler.isEuler) === false ) {
  1694. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1695. }
  1696. if ( quaternion === undefined ) quaternion = new Quaternion();
  1697. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1698. };
  1699. }(),
  1700. applyAxisAngle: function () {
  1701. var quaternion;
  1702. return function applyAxisAngle( axis, angle ) {
  1703. if ( quaternion === undefined ) quaternion = new Quaternion();
  1704. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1705. };
  1706. }(),
  1707. applyMatrix3: function ( m ) {
  1708. var x = this.x, y = this.y, z = this.z;
  1709. var e = m.elements;
  1710. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1711. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1712. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1713. return this;
  1714. },
  1715. applyMatrix4: function ( m ) {
  1716. // input: THREE.Matrix4 affine matrix
  1717. var x = this.x, y = this.y, z = this.z;
  1718. var e = m.elements;
  1719. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1720. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1721. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1722. return this;
  1723. },
  1724. applyProjection: function ( m ) {
  1725. // input: THREE.Matrix4 projection matrix
  1726. var x = this.x, y = this.y, z = this.z;
  1727. var e = m.elements;
  1728. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1729. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1730. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1731. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1732. return this;
  1733. },
  1734. applyQuaternion: function ( q ) {
  1735. var x = this.x, y = this.y, z = this.z;
  1736. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1737. // calculate quat * vector
  1738. var ix = qw * x + qy * z - qz * y;
  1739. var iy = qw * y + qz * x - qx * z;
  1740. var iz = qw * z + qx * y - qy * x;
  1741. var iw = - qx * x - qy * y - qz * z;
  1742. // calculate result * inverse quat
  1743. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1744. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1745. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1746. return this;
  1747. },
  1748. project: function () {
  1749. var matrix;
  1750. return function project( camera ) {
  1751. if ( matrix === undefined ) matrix = new Matrix4();
  1752. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1753. return this.applyProjection( matrix );
  1754. };
  1755. }(),
  1756. unproject: function () {
  1757. var matrix;
  1758. return function unproject( camera ) {
  1759. if ( matrix === undefined ) matrix = new Matrix4();
  1760. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1761. return this.applyProjection( matrix );
  1762. };
  1763. }(),
  1764. transformDirection: function ( m ) {
  1765. // input: THREE.Matrix4 affine matrix
  1766. // vector interpreted as a direction
  1767. var x = this.x, y = this.y, z = this.z;
  1768. var e = m.elements;
  1769. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1770. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1771. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1772. return this.normalize();
  1773. },
  1774. divide: function ( v ) {
  1775. this.x /= v.x;
  1776. this.y /= v.y;
  1777. this.z /= v.z;
  1778. return this;
  1779. },
  1780. divideScalar: function ( scalar ) {
  1781. return this.multiplyScalar( 1 / scalar );
  1782. },
  1783. min: function ( v ) {
  1784. this.x = Math.min( this.x, v.x );
  1785. this.y = Math.min( this.y, v.y );
  1786. this.z = Math.min( this.z, v.z );
  1787. return this;
  1788. },
  1789. max: function ( v ) {
  1790. this.x = Math.max( this.x, v.x );
  1791. this.y = Math.max( this.y, v.y );
  1792. this.z = Math.max( this.z, v.z );
  1793. return this;
  1794. },
  1795. clamp: function ( min, max ) {
  1796. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1797. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1798. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1799. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1800. return this;
  1801. },
  1802. clampScalar: function () {
  1803. var min, max;
  1804. return function clampScalar( minVal, maxVal ) {
  1805. if ( min === undefined ) {
  1806. min = new Vector3();
  1807. max = new Vector3();
  1808. }
  1809. min.set( minVal, minVal, minVal );
  1810. max.set( maxVal, maxVal, maxVal );
  1811. return this.clamp( min, max );
  1812. };
  1813. }(),
  1814. clampLength: function ( min, max ) {
  1815. var length = this.length();
  1816. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1817. },
  1818. floor: function () {
  1819. this.x = Math.floor( this.x );
  1820. this.y = Math.floor( this.y );
  1821. this.z = Math.floor( this.z );
  1822. return this;
  1823. },
  1824. ceil: function () {
  1825. this.x = Math.ceil( this.x );
  1826. this.y = Math.ceil( this.y );
  1827. this.z = Math.ceil( this.z );
  1828. return this;
  1829. },
  1830. round: function () {
  1831. this.x = Math.round( this.x );
  1832. this.y = Math.round( this.y );
  1833. this.z = Math.round( this.z );
  1834. return this;
  1835. },
  1836. roundToZero: function () {
  1837. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1838. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1839. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1840. return this;
  1841. },
  1842. negate: function () {
  1843. this.x = - this.x;
  1844. this.y = - this.y;
  1845. this.z = - this.z;
  1846. return this;
  1847. },
  1848. dot: function ( v ) {
  1849. return this.x * v.x + this.y * v.y + this.z * v.z;
  1850. },
  1851. lengthSq: function () {
  1852. return this.x * this.x + this.y * this.y + this.z * this.z;
  1853. },
  1854. length: function () {
  1855. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1856. },
  1857. lengthManhattan: function () {
  1858. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1859. },
  1860. normalize: function () {
  1861. return this.divideScalar( this.length() );
  1862. },
  1863. setLength: function ( length ) {
  1864. return this.multiplyScalar( length / this.length() );
  1865. },
  1866. lerp: function ( v, alpha ) {
  1867. this.x += ( v.x - this.x ) * alpha;
  1868. this.y += ( v.y - this.y ) * alpha;
  1869. this.z += ( v.z - this.z ) * alpha;
  1870. return this;
  1871. },
  1872. lerpVectors: function ( v1, v2, alpha ) {
  1873. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1874. },
  1875. cross: function ( v, w ) {
  1876. if ( w !== undefined ) {
  1877. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1878. return this.crossVectors( v, w );
  1879. }
  1880. var x = this.x, y = this.y, z = this.z;
  1881. this.x = y * v.z - z * v.y;
  1882. this.y = z * v.x - x * v.z;
  1883. this.z = x * v.y - y * v.x;
  1884. return this;
  1885. },
  1886. crossVectors: function ( a, b ) {
  1887. var ax = a.x, ay = a.y, az = a.z;
  1888. var bx = b.x, by = b.y, bz = b.z;
  1889. this.x = ay * bz - az * by;
  1890. this.y = az * bx - ax * bz;
  1891. this.z = ax * by - ay * bx;
  1892. return this;
  1893. },
  1894. projectOnVector: function ( vector ) {
  1895. var scalar = vector.dot( this ) / vector.lengthSq();
  1896. return this.copy( vector ).multiplyScalar( scalar );
  1897. },
  1898. projectOnPlane: function () {
  1899. var v1;
  1900. return function projectOnPlane( planeNormal ) {
  1901. if ( v1 === undefined ) v1 = new Vector3();
  1902. v1.copy( this ).projectOnVector( planeNormal );
  1903. return this.sub( v1 );
  1904. };
  1905. }(),
  1906. reflect: function () {
  1907. // reflect incident vector off plane orthogonal to normal
  1908. // normal is assumed to have unit length
  1909. var v1;
  1910. return function reflect( normal ) {
  1911. if ( v1 === undefined ) v1 = new Vector3();
  1912. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1913. };
  1914. }(),
  1915. angleTo: function ( v ) {
  1916. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1917. // clamp, to handle numerical problems
  1918. return Math.acos( exports.Math.clamp( theta, - 1, 1 ) );
  1919. },
  1920. distanceTo: function ( v ) {
  1921. return Math.sqrt( this.distanceToSquared( v ) );
  1922. },
  1923. distanceToSquared: function ( v ) {
  1924. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1925. return dx * dx + dy * dy + dz * dz;
  1926. },
  1927. distanceToManhattan: function ( v ) {
  1928. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1929. },
  1930. setFromSpherical: function( s ) {
  1931. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1932. this.x = sinPhiRadius * Math.sin( s.theta );
  1933. this.y = Math.cos( s.phi ) * s.radius;
  1934. this.z = sinPhiRadius * Math.cos( s.theta );
  1935. return this;
  1936. },
  1937. setFromMatrixPosition: function ( m ) {
  1938. return this.setFromMatrixColumn( m, 3 );
  1939. },
  1940. setFromMatrixScale: function ( m ) {
  1941. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1942. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1943. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1944. this.x = sx;
  1945. this.y = sy;
  1946. this.z = sz;
  1947. return this;
  1948. },
  1949. setFromMatrixColumn: function ( m, index ) {
  1950. if ( typeof m === 'number' ) {
  1951. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1952. var temp = m
  1953. m = index;
  1954. index = temp;
  1955. }
  1956. return this.fromArray( m.elements, index * 4 );
  1957. },
  1958. equals: function ( v ) {
  1959. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1960. },
  1961. fromArray: function ( array, offset ) {
  1962. if ( offset === undefined ) offset = 0;
  1963. this.x = array[ offset ];
  1964. this.y = array[ offset + 1 ];
  1965. this.z = array[ offset + 2 ];
  1966. return this;
  1967. },
  1968. toArray: function ( array, offset ) {
  1969. if ( array === undefined ) array = [];
  1970. if ( offset === undefined ) offset = 0;
  1971. array[ offset ] = this.x;
  1972. array[ offset + 1 ] = this.y;
  1973. array[ offset + 2 ] = this.z;
  1974. return array;
  1975. },
  1976. fromAttribute: function ( attribute, index, offset ) {
  1977. if ( offset === undefined ) offset = 0;
  1978. index = index * attribute.itemSize + offset;
  1979. this.x = attribute.array[ index ];
  1980. this.y = attribute.array[ index + 1 ];
  1981. this.z = attribute.array[ index + 2 ];
  1982. return this;
  1983. }
  1984. };
  1985. /**
  1986. * @author mrdoob / http://mrdoob.com/
  1987. * @author supereggbert / http://www.paulbrunt.co.uk/
  1988. * @author philogb / http://blog.thejit.org/
  1989. * @author jordi_ros / http://plattsoft.com
  1990. * @author D1plo1d / http://github.com/D1plo1d
  1991. * @author alteredq / http://alteredqualia.com/
  1992. * @author mikael emtinger / http://gomo.se/
  1993. * @author timknip / http://www.floorplanner.com/
  1994. * @author bhouston / http://clara.io
  1995. * @author WestLangley / http://github.com/WestLangley
  1996. */
  1997. function Matrix4() {
  1998. this.elements = new Float32Array( [
  1999. 1, 0, 0, 0,
  2000. 0, 1, 0, 0,
  2001. 0, 0, 1, 0,
  2002. 0, 0, 0, 1
  2003. ] );
  2004. if ( arguments.length > 0 ) {
  2005. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2006. }
  2007. }
  2008. Matrix4.prototype = {
  2009. constructor: Matrix4,
  2010. isMatrix4: true,
  2011. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2012. var te = this.elements;
  2013. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2014. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2015. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2016. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2017. return this;
  2018. },
  2019. identity: function () {
  2020. this.set(
  2021. 1, 0, 0, 0,
  2022. 0, 1, 0, 0,
  2023. 0, 0, 1, 0,
  2024. 0, 0, 0, 1
  2025. );
  2026. return this;
  2027. },
  2028. clone: function () {
  2029. return new Matrix4().fromArray( this.elements );
  2030. },
  2031. copy: function ( m ) {
  2032. this.elements.set( m.elements );
  2033. return this;
  2034. },
  2035. copyPosition: function ( m ) {
  2036. var te = this.elements;
  2037. var me = m.elements;
  2038. te[ 12 ] = me[ 12 ];
  2039. te[ 13 ] = me[ 13 ];
  2040. te[ 14 ] = me[ 14 ];
  2041. return this;
  2042. },
  2043. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2044. xAxis.setFromMatrixColumn( this, 0 );
  2045. yAxis.setFromMatrixColumn( this, 1 );
  2046. zAxis.setFromMatrixColumn( this, 2 );
  2047. return this;
  2048. },
  2049. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2050. this.set(
  2051. xAxis.x, yAxis.x, zAxis.x, 0,
  2052. xAxis.y, yAxis.y, zAxis.y, 0,
  2053. xAxis.z, yAxis.z, zAxis.z, 0,
  2054. 0, 0, 0, 1
  2055. );
  2056. return this;
  2057. },
  2058. extractRotation: function () {
  2059. var v1;
  2060. return function extractRotation( m ) {
  2061. if ( v1 === undefined ) v1 = new Vector3();
  2062. var te = this.elements;
  2063. var me = m.elements;
  2064. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2065. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2066. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2067. te[ 0 ] = me[ 0 ] * scaleX;
  2068. te[ 1 ] = me[ 1 ] * scaleX;
  2069. te[ 2 ] = me[ 2 ] * scaleX;
  2070. te[ 4 ] = me[ 4 ] * scaleY;
  2071. te[ 5 ] = me[ 5 ] * scaleY;
  2072. te[ 6 ] = me[ 6 ] * scaleY;
  2073. te[ 8 ] = me[ 8 ] * scaleZ;
  2074. te[ 9 ] = me[ 9 ] * scaleZ;
  2075. te[ 10 ] = me[ 10 ] * scaleZ;
  2076. return this;
  2077. };
  2078. }(),
  2079. makeRotationFromEuler: function ( euler ) {
  2080. if ( (euler && euler.isEuler) === false ) {
  2081. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2082. }
  2083. var te = this.elements;
  2084. var x = euler.x, y = euler.y, z = euler.z;
  2085. var a = Math.cos( x ), b = Math.sin( x );
  2086. var c = Math.cos( y ), d = Math.sin( y );
  2087. var e = Math.cos( z ), f = Math.sin( z );
  2088. if ( euler.order === 'XYZ' ) {
  2089. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2090. te[ 0 ] = c * e;
  2091. te[ 4 ] = - c * f;
  2092. te[ 8 ] = d;
  2093. te[ 1 ] = af + be * d;
  2094. te[ 5 ] = ae - bf * d;
  2095. te[ 9 ] = - b * c;
  2096. te[ 2 ] = bf - ae * d;
  2097. te[ 6 ] = be + af * d;
  2098. te[ 10 ] = a * c;
  2099. } else if ( euler.order === 'YXZ' ) {
  2100. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2101. te[ 0 ] = ce + df * b;
  2102. te[ 4 ] = de * b - cf;
  2103. te[ 8 ] = a * d;
  2104. te[ 1 ] = a * f;
  2105. te[ 5 ] = a * e;
  2106. te[ 9 ] = - b;
  2107. te[ 2 ] = cf * b - de;
  2108. te[ 6 ] = df + ce * b;
  2109. te[ 10 ] = a * c;
  2110. } else if ( euler.order === 'ZXY' ) {
  2111. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2112. te[ 0 ] = ce - df * b;
  2113. te[ 4 ] = - a * f;
  2114. te[ 8 ] = de + cf * b;
  2115. te[ 1 ] = cf + de * b;
  2116. te[ 5 ] = a * e;
  2117. te[ 9 ] = df - ce * b;
  2118. te[ 2 ] = - a * d;
  2119. te[ 6 ] = b;
  2120. te[ 10 ] = a * c;
  2121. } else if ( euler.order === 'ZYX' ) {
  2122. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2123. te[ 0 ] = c * e;
  2124. te[ 4 ] = be * d - af;
  2125. te[ 8 ] = ae * d + bf;
  2126. te[ 1 ] = c * f;
  2127. te[ 5 ] = bf * d + ae;
  2128. te[ 9 ] = af * d - be;
  2129. te[ 2 ] = - d;
  2130. te[ 6 ] = b * c;
  2131. te[ 10 ] = a * c;
  2132. } else if ( euler.order === 'YZX' ) {
  2133. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2134. te[ 0 ] = c * e;
  2135. te[ 4 ] = bd - ac * f;
  2136. te[ 8 ] = bc * f + ad;
  2137. te[ 1 ] = f;
  2138. te[ 5 ] = a * e;
  2139. te[ 9 ] = - b * e;
  2140. te[ 2 ] = - d * e;
  2141. te[ 6 ] = ad * f + bc;
  2142. te[ 10 ] = ac - bd * f;
  2143. } else if ( euler.order === 'XZY' ) {
  2144. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2145. te[ 0 ] = c * e;
  2146. te[ 4 ] = - f;
  2147. te[ 8 ] = d * e;
  2148. te[ 1 ] = ac * f + bd;
  2149. te[ 5 ] = a * e;
  2150. te[ 9 ] = ad * f - bc;
  2151. te[ 2 ] = bc * f - ad;
  2152. te[ 6 ] = b * e;
  2153. te[ 10 ] = bd * f + ac;
  2154. }
  2155. // last column
  2156. te[ 3 ] = 0;
  2157. te[ 7 ] = 0;
  2158. te[ 11 ] = 0;
  2159. // bottom row
  2160. te[ 12 ] = 0;
  2161. te[ 13 ] = 0;
  2162. te[ 14 ] = 0;
  2163. te[ 15 ] = 1;
  2164. return this;
  2165. },
  2166. makeRotationFromQuaternion: function ( q ) {
  2167. var te = this.elements;
  2168. var x = q.x, y = q.y, z = q.z, w = q.w;
  2169. var x2 = x + x, y2 = y + y, z2 = z + z;
  2170. var xx = x * x2, xy = x * y2, xz = x * z2;
  2171. var yy = y * y2, yz = y * z2, zz = z * z2;
  2172. var wx = w * x2, wy = w * y2, wz = w * z2;
  2173. te[ 0 ] = 1 - ( yy + zz );
  2174. te[ 4 ] = xy - wz;
  2175. te[ 8 ] = xz + wy;
  2176. te[ 1 ] = xy + wz;
  2177. te[ 5 ] = 1 - ( xx + zz );
  2178. te[ 9 ] = yz - wx;
  2179. te[ 2 ] = xz - wy;
  2180. te[ 6 ] = yz + wx;
  2181. te[ 10 ] = 1 - ( xx + yy );
  2182. // last column
  2183. te[ 3 ] = 0;
  2184. te[ 7 ] = 0;
  2185. te[ 11 ] = 0;
  2186. // bottom row
  2187. te[ 12 ] = 0;
  2188. te[ 13 ] = 0;
  2189. te[ 14 ] = 0;
  2190. te[ 15 ] = 1;
  2191. return this;
  2192. },
  2193. lookAt: function () {
  2194. var x, y, z;
  2195. return function lookAt( eye, target, up ) {
  2196. if ( x === undefined ) {
  2197. x = new Vector3();
  2198. y = new Vector3();
  2199. z = new Vector3();
  2200. }
  2201. var te = this.elements;
  2202. z.subVectors( eye, target ).normalize();
  2203. if ( z.lengthSq() === 0 ) {
  2204. z.z = 1;
  2205. }
  2206. x.crossVectors( up, z ).normalize();
  2207. if ( x.lengthSq() === 0 ) {
  2208. z.z += 0.0001;
  2209. x.crossVectors( up, z ).normalize();
  2210. }
  2211. y.crossVectors( z, x );
  2212. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2213. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2214. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2215. return this;
  2216. };
  2217. }(),
  2218. multiply: function ( m, n ) {
  2219. if ( n !== undefined ) {
  2220. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2221. return this.multiplyMatrices( m, n );
  2222. }
  2223. return this.multiplyMatrices( this, m );
  2224. },
  2225. premultiply: function ( m ) {
  2226. return this.multiplyMatrices( m, this );
  2227. },
  2228. multiplyMatrices: function ( a, b ) {
  2229. var ae = a.elements;
  2230. var be = b.elements;
  2231. var te = this.elements;
  2232. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2233. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2234. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2235. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2236. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2237. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2238. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2239. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2240. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2241. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2242. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2243. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2244. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2245. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2246. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2247. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2248. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2249. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2250. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2251. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2252. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2253. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2254. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2255. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2256. return this;
  2257. },
  2258. multiplyToArray: function ( a, b, r ) {
  2259. var te = this.elements;
  2260. this.multiplyMatrices( a, b );
  2261. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2262. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2263. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2264. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2265. return this;
  2266. },
  2267. multiplyScalar: function ( s ) {
  2268. var te = this.elements;
  2269. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2270. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2271. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2272. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2273. return this;
  2274. },
  2275. applyToVector3Array: function () {
  2276. var v1;
  2277. return function applyToVector3Array( array, offset, length ) {
  2278. if ( v1 === undefined ) v1 = new Vector3();
  2279. if ( offset === undefined ) offset = 0;
  2280. if ( length === undefined ) length = array.length;
  2281. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2282. v1.fromArray( array, j );
  2283. v1.applyMatrix4( this );
  2284. v1.toArray( array, j );
  2285. }
  2286. return array;
  2287. };
  2288. }(),
  2289. applyToBuffer: function () {
  2290. var v1;
  2291. return function applyToBuffer( buffer, offset, length ) {
  2292. if ( v1 === undefined ) v1 = new Vector3();
  2293. if ( offset === undefined ) offset = 0;
  2294. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2295. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2296. v1.x = buffer.getX( j );
  2297. v1.y = buffer.getY( j );
  2298. v1.z = buffer.getZ( j );
  2299. v1.applyMatrix4( this );
  2300. buffer.setXYZ( v1.x, v1.y, v1.z );
  2301. }
  2302. return buffer;
  2303. };
  2304. }(),
  2305. determinant: function () {
  2306. var te = this.elements;
  2307. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2308. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2309. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2310. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2311. //TODO: make this more efficient
  2312. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2313. return (
  2314. n41 * (
  2315. + n14 * n23 * n32
  2316. - n13 * n24 * n32
  2317. - n14 * n22 * n33
  2318. + n12 * n24 * n33
  2319. + n13 * n22 * n34
  2320. - n12 * n23 * n34
  2321. ) +
  2322. n42 * (
  2323. + n11 * n23 * n34
  2324. - n11 * n24 * n33
  2325. + n14 * n21 * n33
  2326. - n13 * n21 * n34
  2327. + n13 * n24 * n31
  2328. - n14 * n23 * n31
  2329. ) +
  2330. n43 * (
  2331. + n11 * n24 * n32
  2332. - n11 * n22 * n34
  2333. - n14 * n21 * n32
  2334. + n12 * n21 * n34
  2335. + n14 * n22 * n31
  2336. - n12 * n24 * n31
  2337. ) +
  2338. n44 * (
  2339. - n13 * n22 * n31
  2340. - n11 * n23 * n32
  2341. + n11 * n22 * n33
  2342. + n13 * n21 * n32
  2343. - n12 * n21 * n33
  2344. + n12 * n23 * n31
  2345. )
  2346. );
  2347. },
  2348. transpose: function () {
  2349. var te = this.elements;
  2350. var tmp;
  2351. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2352. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2353. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2354. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2355. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2356. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2357. return this;
  2358. },
  2359. flattenToArrayOffset: function ( array, offset ) {
  2360. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  2361. "- just use .toArray instead." );
  2362. return this.toArray( array, offset );
  2363. },
  2364. getPosition: function () {
  2365. var v1;
  2366. return function getPosition() {
  2367. if ( v1 === undefined ) v1 = new Vector3();
  2368. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2369. return v1.setFromMatrixColumn( this, 3 );
  2370. };
  2371. }(),
  2372. setPosition: function ( v ) {
  2373. var te = this.elements;
  2374. te[ 12 ] = v.x;
  2375. te[ 13 ] = v.y;
  2376. te[ 14 ] = v.z;
  2377. return this;
  2378. },
  2379. getInverse: function ( m, throwOnDegenerate ) {
  2380. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2381. var te = this.elements,
  2382. me = m.elements,
  2383. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2384. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2385. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2386. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2387. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2388. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2389. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2390. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2391. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2392. if ( det === 0 ) {
  2393. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2394. if ( throwOnDegenerate === true ) {
  2395. throw new Error( msg );
  2396. } else {
  2397. console.warn( msg );
  2398. }
  2399. return this.identity();
  2400. }
  2401. var detInv = 1 / det;
  2402. te[ 0 ] = t11 * detInv;
  2403. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2404. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2405. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2406. te[ 4 ] = t12 * detInv;
  2407. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2408. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2409. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2410. te[ 8 ] = t13 * detInv;
  2411. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2412. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2413. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2414. te[ 12 ] = t14 * detInv;
  2415. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2416. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2417. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2418. return this;
  2419. },
  2420. scale: function ( v ) {
  2421. var te = this.elements;
  2422. var x = v.x, y = v.y, z = v.z;
  2423. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2424. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2425. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2426. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2427. return this;
  2428. },
  2429. getMaxScaleOnAxis: function () {
  2430. var te = this.elements;
  2431. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2432. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2433. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2434. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2435. },
  2436. makeTranslation: function ( x, y, z ) {
  2437. this.set(
  2438. 1, 0, 0, x,
  2439. 0, 1, 0, y,
  2440. 0, 0, 1, z,
  2441. 0, 0, 0, 1
  2442. );
  2443. return this;
  2444. },
  2445. makeRotationX: function ( theta ) {
  2446. var c = Math.cos( theta ), s = Math.sin( theta );
  2447. this.set(
  2448. 1, 0, 0, 0,
  2449. 0, c, - s, 0,
  2450. 0, s, c, 0,
  2451. 0, 0, 0, 1
  2452. );
  2453. return this;
  2454. },
  2455. makeRotationY: function ( theta ) {
  2456. var c = Math.cos( theta ), s = Math.sin( theta );
  2457. this.set(
  2458. c, 0, s, 0,
  2459. 0, 1, 0, 0,
  2460. - s, 0, c, 0,
  2461. 0, 0, 0, 1
  2462. );
  2463. return this;
  2464. },
  2465. makeRotationZ: function ( theta ) {
  2466. var c = Math.cos( theta ), s = Math.sin( theta );
  2467. this.set(
  2468. c, - s, 0, 0,
  2469. s, c, 0, 0,
  2470. 0, 0, 1, 0,
  2471. 0, 0, 0, 1
  2472. );
  2473. return this;
  2474. },
  2475. makeRotationAxis: function ( axis, angle ) {
  2476. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2477. var c = Math.cos( angle );
  2478. var s = Math.sin( angle );
  2479. var t = 1 - c;
  2480. var x = axis.x, y = axis.y, z = axis.z;
  2481. var tx = t * x, ty = t * y;
  2482. this.set(
  2483. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2484. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2485. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2486. 0, 0, 0, 1
  2487. );
  2488. return this;
  2489. },
  2490. makeScale: function ( x, y, z ) {
  2491. this.set(
  2492. x, 0, 0, 0,
  2493. 0, y, 0, 0,
  2494. 0, 0, z, 0,
  2495. 0, 0, 0, 1
  2496. );
  2497. return this;
  2498. },
  2499. compose: function ( position, quaternion, scale ) {
  2500. this.makeRotationFromQuaternion( quaternion );
  2501. this.scale( scale );
  2502. this.setPosition( position );
  2503. return this;
  2504. },
  2505. decompose: function () {
  2506. var vector, matrix;
  2507. return function decompose( position, quaternion, scale ) {
  2508. if ( vector === undefined ) {
  2509. vector = new Vector3();
  2510. matrix = new Matrix4();
  2511. }
  2512. var te = this.elements;
  2513. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2514. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2515. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2516. // if determine is negative, we need to invert one scale
  2517. var det = this.determinant();
  2518. if ( det < 0 ) {
  2519. sx = - sx;
  2520. }
  2521. position.x = te[ 12 ];
  2522. position.y = te[ 13 ];
  2523. position.z = te[ 14 ];
  2524. // scale the rotation part
  2525. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2526. var invSX = 1 / sx;
  2527. var invSY = 1 / sy;
  2528. var invSZ = 1 / sz;
  2529. matrix.elements[ 0 ] *= invSX;
  2530. matrix.elements[ 1 ] *= invSX;
  2531. matrix.elements[ 2 ] *= invSX;
  2532. matrix.elements[ 4 ] *= invSY;
  2533. matrix.elements[ 5 ] *= invSY;
  2534. matrix.elements[ 6 ] *= invSY;
  2535. matrix.elements[ 8 ] *= invSZ;
  2536. matrix.elements[ 9 ] *= invSZ;
  2537. matrix.elements[ 10 ] *= invSZ;
  2538. quaternion.setFromRotationMatrix( matrix );
  2539. scale.x = sx;
  2540. scale.y = sy;
  2541. scale.z = sz;
  2542. return this;
  2543. };
  2544. }(),
  2545. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2546. var te = this.elements;
  2547. var x = 2 * near / ( right - left );
  2548. var y = 2 * near / ( top - bottom );
  2549. var a = ( right + left ) / ( right - left );
  2550. var b = ( top + bottom ) / ( top - bottom );
  2551. var c = - ( far + near ) / ( far - near );
  2552. var d = - 2 * far * near / ( far - near );
  2553. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2554. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2555. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2556. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2557. return this;
  2558. },
  2559. makePerspective: function ( fov, aspect, near, far ) {
  2560. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  2561. var ymin = - ymax;
  2562. var xmin = ymin * aspect;
  2563. var xmax = ymax * aspect;
  2564. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2565. },
  2566. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2567. var te = this.elements;
  2568. var w = 1.0 / ( right - left );
  2569. var h = 1.0 / ( top - bottom );
  2570. var p = 1.0 / ( far - near );
  2571. var x = ( right + left ) * w;
  2572. var y = ( top + bottom ) * h;
  2573. var z = ( far + near ) * p;
  2574. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2575. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2576. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2577. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2578. return this;
  2579. },
  2580. equals: function ( matrix ) {
  2581. var te = this.elements;
  2582. var me = matrix.elements;
  2583. for ( var i = 0; i < 16; i ++ ) {
  2584. if ( te[ i ] !== me[ i ] ) return false;
  2585. }
  2586. return true;
  2587. },
  2588. fromArray: function ( array ) {
  2589. this.elements.set( array );
  2590. return this;
  2591. },
  2592. toArray: function ( array, offset ) {
  2593. if ( array === undefined ) array = [];
  2594. if ( offset === undefined ) offset = 0;
  2595. var te = this.elements;
  2596. array[ offset ] = te[ 0 ];
  2597. array[ offset + 1 ] = te[ 1 ];
  2598. array[ offset + 2 ] = te[ 2 ];
  2599. array[ offset + 3 ] = te[ 3 ];
  2600. array[ offset + 4 ] = te[ 4 ];
  2601. array[ offset + 5 ] = te[ 5 ];
  2602. array[ offset + 6 ] = te[ 6 ];
  2603. array[ offset + 7 ] = te[ 7 ];
  2604. array[ offset + 8 ] = te[ 8 ];
  2605. array[ offset + 9 ] = te[ 9 ];
  2606. array[ offset + 10 ] = te[ 10 ];
  2607. array[ offset + 11 ] = te[ 11 ];
  2608. array[ offset + 12 ] = te[ 12 ];
  2609. array[ offset + 13 ] = te[ 13 ];
  2610. array[ offset + 14 ] = te[ 14 ];
  2611. array[ offset + 15 ] = te[ 15 ];
  2612. return array;
  2613. }
  2614. };
  2615. /**
  2616. * @author mrdoob / http://mrdoob.com/
  2617. */
  2618. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2619. images = images !== undefined ? images : [];
  2620. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2621. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2622. this.flipY = false;
  2623. }
  2624. CubeTexture.prototype = Object.create( Texture.prototype );
  2625. CubeTexture.prototype.constructor = CubeTexture;
  2626. CubeTexture.prototype.isCubeTexture = true;
  2627. Object.defineProperty( CubeTexture.prototype, 'images', {
  2628. get: function () {
  2629. return this.image;
  2630. },
  2631. set: function ( value ) {
  2632. this.image = value;
  2633. }
  2634. } );
  2635. var emptyTexture = new Texture();
  2636. var emptyCubeTexture = new CubeTexture();
  2637. // --- Base for inner nodes (including the root) ---
  2638. function UniformContainer() {
  2639. this.seq = [];
  2640. this.map = {};
  2641. }
  2642. // --- Utilities ---
  2643. // Array Caches (provide typed arrays for temporary by size)
  2644. var arrayCacheF32 = [];
  2645. var arrayCacheI32 = [];
  2646. // Flattening for arrays of vectors and matrices
  2647. function flatten( array, nBlocks, blockSize ) {
  2648. var firstElem = array[ 0 ];
  2649. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2650. // unoptimized: ! isNaN( firstElem )
  2651. // see http://jacksondunstan.com/articles/983
  2652. var n = nBlocks * blockSize,
  2653. r = arrayCacheF32[ n ];
  2654. if ( r === undefined ) {
  2655. r = new Float32Array( n );
  2656. arrayCacheF32[ n ] = r;
  2657. }
  2658. if ( nBlocks !== 0 ) {
  2659. firstElem.toArray( r, 0 );
  2660. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2661. offset += blockSize;
  2662. array[ i ].toArray( r, offset );
  2663. }
  2664. }
  2665. return r;
  2666. }
  2667. // Texture unit allocation
  2668. function allocTexUnits( renderer, n ) {
  2669. var r = arrayCacheI32[ n ];
  2670. if ( r === undefined ) {
  2671. r = new Int32Array( n );
  2672. arrayCacheI32[ n ] = r;
  2673. }
  2674. for ( var i = 0; i !== n; ++ i )
  2675. r[ i ] = renderer.allocTextureUnit();
  2676. return r;
  2677. }
  2678. // --- Setters ---
  2679. // Note: Defining these methods externally, because they come in a bunch
  2680. // and this way their names minify.
  2681. // Single scalar
  2682. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2683. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2684. // Single float vector (from flat array or THREE.VectorN)
  2685. function setValue2fv( gl, v ) {
  2686. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2687. else gl.uniform2f( this.addr, v.x, v.y );
  2688. }
  2689. function setValue3fv( gl, v ) {
  2690. if ( v.x !== undefined )
  2691. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2692. else if ( v.r !== undefined )
  2693. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2694. else
  2695. gl.uniform3fv( this.addr, v );
  2696. }
  2697. function setValue4fv( gl, v ) {
  2698. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2699. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2700. }
  2701. // Single matrix (from flat array or MatrixN)
  2702. function setValue2fm( gl, v ) {
  2703. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2704. }
  2705. function setValue3fm( gl, v ) {
  2706. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2707. }
  2708. function setValue4fm( gl, v ) {
  2709. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2710. }
  2711. // Single texture (2D / Cube)
  2712. function setValueT1( gl, v, renderer ) {
  2713. var unit = renderer.allocTextureUnit();
  2714. gl.uniform1i( this.addr, unit );
  2715. renderer.setTexture2D( v || emptyTexture, unit );
  2716. }
  2717. function setValueT6( gl, v, renderer ) {
  2718. var unit = renderer.allocTextureUnit();
  2719. gl.uniform1i( this.addr, unit );
  2720. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2721. }
  2722. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2723. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2724. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2725. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2726. // Helper to pick the right setter for the singular case
  2727. function getSingularSetter( type ) {
  2728. switch ( type ) {
  2729. case 0x1406: return setValue1f; // FLOAT
  2730. case 0x8b50: return setValue2fv; // _VEC2
  2731. case 0x8b51: return setValue3fv; // _VEC3
  2732. case 0x8b52: return setValue4fv; // _VEC4
  2733. case 0x8b5a: return setValue2fm; // _MAT2
  2734. case 0x8b5b: return setValue3fm; // _MAT3
  2735. case 0x8b5c: return setValue4fm; // _MAT4
  2736. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2737. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2738. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2739. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2740. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2741. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2742. }
  2743. }
  2744. // Array of scalars
  2745. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2746. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2747. // Array of vectors (flat or from THREE classes)
  2748. function setValueV2a( gl, v ) {
  2749. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2750. }
  2751. function setValueV3a( gl, v ) {
  2752. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2753. }
  2754. function setValueV4a( gl, v ) {
  2755. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2756. }
  2757. // Array of matrices (flat or from THREE clases)
  2758. function setValueM2a( gl, v ) {
  2759. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2760. }
  2761. function setValueM3a( gl, v ) {
  2762. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2763. }
  2764. function setValueM4a( gl, v ) {
  2765. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2766. }
  2767. // Array of textures (2D / Cube)
  2768. function setValueT1a( gl, v, renderer ) {
  2769. var n = v.length,
  2770. units = allocTexUnits( renderer, n );
  2771. gl.uniform1iv( this.addr, units );
  2772. for ( var i = 0; i !== n; ++ i ) {
  2773. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2774. }
  2775. }
  2776. function setValueT6a( gl, v, renderer ) {
  2777. var n = v.length,
  2778. units = allocTexUnits( renderer, n );
  2779. gl.uniform1iv( this.addr, units );
  2780. for ( var i = 0; i !== n; ++ i ) {
  2781. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2782. }
  2783. }
  2784. // Helper to pick the right setter for a pure (bottom-level) array
  2785. function getPureArraySetter( type ) {
  2786. switch ( type ) {
  2787. case 0x1406: return setValue1fv; // FLOAT
  2788. case 0x8b50: return setValueV2a; // _VEC2
  2789. case 0x8b51: return setValueV3a; // _VEC3
  2790. case 0x8b52: return setValueV4a; // _VEC4
  2791. case 0x8b5a: return setValueM2a; // _MAT2
  2792. case 0x8b5b: return setValueM3a; // _MAT3
  2793. case 0x8b5c: return setValueM4a; // _MAT4
  2794. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2795. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2796. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2797. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2798. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2799. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2800. }
  2801. }
  2802. // --- Uniform Classes ---
  2803. function SingleUniform( id, activeInfo, addr ) {
  2804. this.id = id;
  2805. this.addr = addr;
  2806. this.setValue = getSingularSetter( activeInfo.type );
  2807. // this.path = activeInfo.name; // DEBUG
  2808. }
  2809. function PureArrayUniform( id, activeInfo, addr ) {
  2810. this.id = id;
  2811. this.addr = addr;
  2812. this.size = activeInfo.size;
  2813. this.setValue = getPureArraySetter( activeInfo.type );
  2814. // this.path = activeInfo.name; // DEBUG
  2815. }
  2816. function StructuredUniform( id ) {
  2817. this.id = id;
  2818. UniformContainer.call( this ); // mix-in
  2819. }
  2820. StructuredUniform.prototype.setValue = function( gl, value ) {
  2821. // Note: Don't need an extra 'renderer' parameter, since samplers
  2822. // are not allowed in structured uniforms.
  2823. var seq = this.seq;
  2824. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2825. var u = seq[ i ];
  2826. u.setValue( gl, value[ u.id ] );
  2827. }
  2828. };
  2829. // --- Top-level ---
  2830. // Parser - builds up the property tree from the path strings
  2831. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2832. // extracts
  2833. // - the identifier (member name or array index)
  2834. // - followed by an optional right bracket (found when array index)
  2835. // - followed by an optional left bracket or dot (type of subscript)
  2836. //
  2837. // Note: These portions can be read in a non-overlapping fashion and
  2838. // allow straightforward parsing of the hierarchy that WebGL encodes
  2839. // in the uniform names.
  2840. function addUniform( container, uniformObject ) {
  2841. container.seq.push( uniformObject );
  2842. container.map[ uniformObject.id ] = uniformObject;
  2843. }
  2844. function parseUniform( activeInfo, addr, container ) {
  2845. var path = activeInfo.name,
  2846. pathLength = path.length;
  2847. // reset RegExp object, because of the early exit of a previous run
  2848. RePathPart.lastIndex = 0;
  2849. for (; ;) {
  2850. var match = RePathPart.exec( path ),
  2851. matchEnd = RePathPart.lastIndex,
  2852. id = match[ 1 ],
  2853. idIsIndex = match[ 2 ] === ']',
  2854. subscript = match[ 3 ];
  2855. if ( idIsIndex ) id = id | 0; // convert to integer
  2856. if ( subscript === undefined ||
  2857. subscript === '[' && matchEnd + 2 === pathLength ) {
  2858. // bare name or "pure" bottom-level array "[0]" suffix
  2859. addUniform( container, subscript === undefined ?
  2860. new SingleUniform( id, activeInfo, addr ) :
  2861. new PureArrayUniform( id, activeInfo, addr ) );
  2862. break;
  2863. } else {
  2864. // step into inner node / create it in case it doesn't exist
  2865. var map = container.map,
  2866. next = map[ id ];
  2867. if ( next === undefined ) {
  2868. next = new StructuredUniform( id );
  2869. addUniform( container, next );
  2870. }
  2871. container = next;
  2872. }
  2873. }
  2874. }
  2875. // Root Container
  2876. function WebGLUniforms( gl, program, renderer ) {
  2877. UniformContainer.call( this );
  2878. this.renderer = renderer;
  2879. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2880. for ( var i = 0; i !== n; ++ i ) {
  2881. var info = gl.getActiveUniform( program, i ),
  2882. path = info.name,
  2883. addr = gl.getUniformLocation( program, path );
  2884. parseUniform( info, addr, this );
  2885. }
  2886. }
  2887. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2888. var u = this.map[ name ];
  2889. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2890. };
  2891. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2892. var u = this.map[ name ];
  2893. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2894. };
  2895. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2896. var v = object[ name ];
  2897. if ( v !== undefined ) this.setValue( gl, name, v );
  2898. };
  2899. // Static interface
  2900. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2901. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2902. var u = seq[ i ],
  2903. v = values[ u.id ];
  2904. if ( v.needsUpdate !== false ) {
  2905. // note: always updating when .needsUpdate is undefined
  2906. u.setValue( gl, v.value, renderer );
  2907. }
  2908. }
  2909. };
  2910. WebGLUniforms.seqWithValue = function( seq, values ) {
  2911. var r = [];
  2912. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2913. var u = seq[ i ];
  2914. if ( u.id in values ) r.push( u );
  2915. }
  2916. return r;
  2917. };
  2918. WebGLUniforms.splitDynamic = function( seq, values ) {
  2919. var r = null,
  2920. n = seq.length,
  2921. w = 0;
  2922. for ( var i = 0; i !== n; ++ i ) {
  2923. var u = seq[ i ],
  2924. v = values[ u.id ];
  2925. if ( v && v.dynamic === true ) {
  2926. if ( r === null ) r = [];
  2927. r.push( u );
  2928. } else {
  2929. // in-place compact 'seq', removing the matches
  2930. if ( w < i ) seq[ w ] = u;
  2931. ++ w;
  2932. }
  2933. }
  2934. if ( w < n ) seq.length = w;
  2935. return r;
  2936. };
  2937. WebGLUniforms.evalDynamic = function( seq, values, object, camera ) {
  2938. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2939. var v = values[ seq[ i ].id ],
  2940. f = v.onUpdateCallback;
  2941. if ( f !== undefined ) f.call( v, object, camera );
  2942. }
  2943. };
  2944. /**
  2945. * Uniform Utilities
  2946. */
  2947. exports.UniformsUtils = {
  2948. merge: function ( uniforms ) {
  2949. var merged = {};
  2950. for ( var u = 0; u < uniforms.length; u ++ ) {
  2951. var tmp = this.clone( uniforms[ u ] );
  2952. for ( var p in tmp ) {
  2953. merged[ p ] = tmp[ p ];
  2954. }
  2955. }
  2956. return merged;
  2957. },
  2958. clone: function ( uniforms_src ) {
  2959. var uniforms_dst = {};
  2960. for ( var u in uniforms_src ) {
  2961. uniforms_dst[ u ] = {};
  2962. for ( var p in uniforms_src[ u ] ) {
  2963. var parameter_src = uniforms_src[ u ][ p ];
  2964. if ( (parameter_src && parameter_src.isColor) ||
  2965. (parameter_src && parameter_src.isVector2) ||
  2966. (parameter_src && parameter_src.isVector3) ||
  2967. (parameter_src && parameter_src.isVector4) ||
  2968. (parameter_src && parameter_src.isMatrix3) ||
  2969. (parameter_src && parameter_src.isMatrix4) ||
  2970. (parameter_src && parameter_src.isTexture) ) {
  2971. uniforms_dst[ u ][ p ] = parameter_src.clone();
  2972. } else if ( Array.isArray( parameter_src ) ) {
  2973. uniforms_dst[ u ][ p ] = parameter_src.slice();
  2974. } else {
  2975. uniforms_dst[ u ][ p ] = parameter_src;
  2976. }
  2977. }
  2978. }
  2979. return uniforms_dst;
  2980. }
  2981. };
  2982. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  2983. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  2984. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  2985. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  2986. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  2987. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  2988. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  2989. var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn 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\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  2990. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  2991. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n#endif\n";
  2992. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  2993. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  2994. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  2995. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  2996. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  2997. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  2998. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  2999. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\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 pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n";
  3000. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  3001. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3002. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3003. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3004. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  3005. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3006. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3007. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3008. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3009. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  3010. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  3011. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  3012. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3013. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  3014. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3015. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3016. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  3017. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include <normal_flip>\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include <normal_flip>\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  3018. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3019. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3020. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  3021. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  3022. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3023. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3024. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  3025. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  3026. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  3027. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3028. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3029. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  3030. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3031. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3032. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3033. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  3034. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  3035. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  3036. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  3037. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  3038. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3039. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3040. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3041. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3042. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3043. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3044. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3045. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  3046. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  3047. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3048. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  3049. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  3050. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3051. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  3052. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  3053. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3054. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3055. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3056. var 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_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  3057. var 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_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  3058. var 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_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  3059. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3060. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3061. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3062. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3063. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3064. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3065. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  3066. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3067. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  3068. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  3069. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3070. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3071. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3072. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3073. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3074. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n}\n";
  3075. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3076. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3077. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3078. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3079. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3080. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3081. var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include <logdepthbuf_fragment>\n}\n";
  3082. var normal_vert = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3083. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3084. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3085. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3086. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3087. var ShaderChunk = {
  3088. alphamap_fragment: alphamap_fragment,
  3089. alphamap_pars_fragment: alphamap_pars_fragment,
  3090. alphatest_fragment: alphatest_fragment,
  3091. aomap_fragment: aomap_fragment,
  3092. aomap_pars_fragment: aomap_pars_fragment,
  3093. begin_vertex: begin_vertex,
  3094. beginnormal_vertex: beginnormal_vertex,
  3095. bsdfs: bsdfs,
  3096. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3097. clipping_planes_fragment: clipping_planes_fragment,
  3098. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3099. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3100. clipping_planes_vertex: clipping_planes_vertex,
  3101. color_fragment: color_fragment,
  3102. color_pars_fragment: color_pars_fragment,
  3103. color_pars_vertex: color_pars_vertex,
  3104. color_vertex: color_vertex,
  3105. common: common,
  3106. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3107. defaultnormal_vertex: defaultnormal_vertex,
  3108. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3109. displacementmap_vertex: displacementmap_vertex,
  3110. emissivemap_fragment: emissivemap_fragment,
  3111. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3112. encodings_fragment: encodings_fragment,
  3113. encodings_pars_fragment: encodings_pars_fragment,
  3114. envmap_fragment: envmap_fragment,
  3115. envmap_pars_fragment: envmap_pars_fragment,
  3116. envmap_pars_vertex: envmap_pars_vertex,
  3117. envmap_vertex: envmap_vertex,
  3118. fog_fragment: fog_fragment,
  3119. fog_pars_fragment: fog_pars_fragment,
  3120. lightmap_fragment: lightmap_fragment,
  3121. lightmap_pars_fragment: lightmap_pars_fragment,
  3122. lights_lambert_vertex: lights_lambert_vertex,
  3123. lights_pars: lights_pars,
  3124. lights_phong_fragment: lights_phong_fragment,
  3125. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3126. lights_physical_fragment: lights_physical_fragment,
  3127. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3128. lights_template: lights_template,
  3129. logdepthbuf_fragment: logdepthbuf_fragment,
  3130. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3131. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3132. logdepthbuf_vertex: logdepthbuf_vertex,
  3133. map_fragment: map_fragment,
  3134. map_pars_fragment: map_pars_fragment,
  3135. map_particle_fragment: map_particle_fragment,
  3136. map_particle_pars_fragment: map_particle_pars_fragment,
  3137. metalnessmap_fragment: metalnessmap_fragment,
  3138. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3139. morphnormal_vertex: morphnormal_vertex,
  3140. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3141. morphtarget_vertex: morphtarget_vertex,
  3142. normal_flip: normal_flip,
  3143. normal_fragment: normal_fragment,
  3144. normalmap_pars_fragment: normalmap_pars_fragment,
  3145. packing: packing,
  3146. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3147. project_vertex: project_vertex,
  3148. roughnessmap_fragment: roughnessmap_fragment,
  3149. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3150. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3151. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3152. shadowmap_vertex: shadowmap_vertex,
  3153. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3154. skinbase_vertex: skinbase_vertex,
  3155. skinning_pars_vertex: skinning_pars_vertex,
  3156. skinning_vertex: skinning_vertex,
  3157. skinnormal_vertex: skinnormal_vertex,
  3158. specularmap_fragment: specularmap_fragment,
  3159. specularmap_pars_fragment: specularmap_pars_fragment,
  3160. tonemapping_fragment: tonemapping_fragment,
  3161. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3162. uv_pars_fragment: uv_pars_fragment,
  3163. uv_pars_vertex: uv_pars_vertex,
  3164. uv_vertex: uv_vertex,
  3165. uv2_pars_fragment: uv2_pars_fragment,
  3166. uv2_pars_vertex: uv2_pars_vertex,
  3167. uv2_vertex: uv2_vertex,
  3168. worldpos_vertex: worldpos_vertex,
  3169. cube_frag: cube_frag,
  3170. cube_vert: cube_vert,
  3171. depth_frag: depth_frag,
  3172. depth_vert: depth_vert,
  3173. distanceRGBA_frag: distanceRGBA_frag,
  3174. distanceRGBA_vert: distanceRGBA_vert,
  3175. equirect_frag: equirect_frag,
  3176. equirect_vert: equirect_vert,
  3177. linedashed_frag: linedashed_frag,
  3178. linedashed_vert: linedashed_vert,
  3179. meshbasic_frag: meshbasic_frag,
  3180. meshbasic_vert: meshbasic_vert,
  3181. meshlambert_frag: meshlambert_frag,
  3182. meshlambert_vert: meshlambert_vert,
  3183. meshphong_frag: meshphong_frag,
  3184. meshphong_vert: meshphong_vert,
  3185. meshphysical_frag: meshphysical_frag,
  3186. meshphysical_vert: meshphysical_vert,
  3187. normal_frag: normal_frag,
  3188. normal_vert: normal_vert,
  3189. points_frag: points_frag,
  3190. points_vert: points_vert,
  3191. shadow_frag: shadow_frag,
  3192. shadow_vert: shadow_vert
  3193. };
  3194. /**
  3195. * @author mrdoob / http://mrdoob.com/
  3196. */
  3197. function Color( r, g, b ) {
  3198. if ( g === undefined && b === undefined ) {
  3199. // r is THREE.Color, hex or string
  3200. return this.set( r );
  3201. }
  3202. return this.setRGB( r, g, b );
  3203. }
  3204. Color.prototype = {
  3205. constructor: Color,
  3206. isColor: true,
  3207. r: 1, g: 1, b: 1,
  3208. set: function ( value ) {
  3209. if ( (value && value.isColor) ) {
  3210. this.copy( value );
  3211. } else if ( typeof value === 'number' ) {
  3212. this.setHex( value );
  3213. } else if ( typeof value === 'string' ) {
  3214. this.setStyle( value );
  3215. }
  3216. return this;
  3217. },
  3218. setScalar: function ( scalar ) {
  3219. this.r = scalar;
  3220. this.g = scalar;
  3221. this.b = scalar;
  3222. },
  3223. setHex: function ( hex ) {
  3224. hex = Math.floor( hex );
  3225. this.r = ( hex >> 16 & 255 ) / 255;
  3226. this.g = ( hex >> 8 & 255 ) / 255;
  3227. this.b = ( hex & 255 ) / 255;
  3228. return this;
  3229. },
  3230. setRGB: function ( r, g, b ) {
  3231. this.r = r;
  3232. this.g = g;
  3233. this.b = b;
  3234. return this;
  3235. },
  3236. setHSL: function () {
  3237. function hue2rgb( p, q, t ) {
  3238. if ( t < 0 ) t += 1;
  3239. if ( t > 1 ) t -= 1;
  3240. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3241. if ( t < 1 / 2 ) return q;
  3242. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3243. return p;
  3244. }
  3245. return function setHSL( h, s, l ) {
  3246. // h,s,l ranges are in 0.0 - 1.0
  3247. h = exports.Math.euclideanModulo( h, 1 );
  3248. s = exports.Math.clamp( s, 0, 1 );
  3249. l = exports.Math.clamp( l, 0, 1 );
  3250. if ( s === 0 ) {
  3251. this.r = this.g = this.b = l;
  3252. } else {
  3253. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3254. var q = ( 2 * l ) - p;
  3255. this.r = hue2rgb( q, p, h + 1 / 3 );
  3256. this.g = hue2rgb( q, p, h );
  3257. this.b = hue2rgb( q, p, h - 1 / 3 );
  3258. }
  3259. return this;
  3260. };
  3261. }(),
  3262. setStyle: function ( style ) {
  3263. function handleAlpha( string ) {
  3264. if ( string === undefined ) return;
  3265. if ( parseFloat( string ) < 1 ) {
  3266. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3267. }
  3268. }
  3269. var m;
  3270. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3271. // rgb / hsl
  3272. var color;
  3273. var name = m[ 1 ];
  3274. var components = m[ 2 ];
  3275. switch ( name ) {
  3276. case 'rgb':
  3277. case 'rgba':
  3278. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3279. // rgb(255,0,0) rgba(255,0,0,0.5)
  3280. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3281. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3282. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3283. handleAlpha( color[ 5 ] );
  3284. return this;
  3285. }
  3286. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3287. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3288. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3289. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3290. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3291. handleAlpha( color[ 5 ] );
  3292. return this;
  3293. }
  3294. break;
  3295. case 'hsl':
  3296. case 'hsla':
  3297. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3298. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3299. var h = parseFloat( color[ 1 ] ) / 360;
  3300. var s = parseInt( color[ 2 ], 10 ) / 100;
  3301. var l = parseInt( color[ 3 ], 10 ) / 100;
  3302. handleAlpha( color[ 5 ] );
  3303. return this.setHSL( h, s, l );
  3304. }
  3305. break;
  3306. }
  3307. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3308. // hex color
  3309. var hex = m[ 1 ];
  3310. var size = hex.length;
  3311. if ( size === 3 ) {
  3312. // #ff0
  3313. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3314. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3315. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3316. return this;
  3317. } else if ( size === 6 ) {
  3318. // #ff0000
  3319. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3320. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3321. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3322. return this;
  3323. }
  3324. }
  3325. if ( style && style.length > 0 ) {
  3326. // color keywords
  3327. var hex = exports.ColorKeywords[ style ];
  3328. if ( hex !== undefined ) {
  3329. // red
  3330. this.setHex( hex );
  3331. } else {
  3332. // unknown color
  3333. console.warn( 'THREE.Color: Unknown color ' + style );
  3334. }
  3335. }
  3336. return this;
  3337. },
  3338. clone: function () {
  3339. return new this.constructor( this.r, this.g, this.b );
  3340. },
  3341. copy: function ( color ) {
  3342. this.r = color.r;
  3343. this.g = color.g;
  3344. this.b = color.b;
  3345. return this;
  3346. },
  3347. copyGammaToLinear: function ( color, gammaFactor ) {
  3348. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3349. this.r = Math.pow( color.r, gammaFactor );
  3350. this.g = Math.pow( color.g, gammaFactor );
  3351. this.b = Math.pow( color.b, gammaFactor );
  3352. return this;
  3353. },
  3354. copyLinearToGamma: function ( color, gammaFactor ) {
  3355. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3356. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3357. this.r = Math.pow( color.r, safeInverse );
  3358. this.g = Math.pow( color.g, safeInverse );
  3359. this.b = Math.pow( color.b, safeInverse );
  3360. return this;
  3361. },
  3362. convertGammaToLinear: function () {
  3363. var r = this.r, g = this.g, b = this.b;
  3364. this.r = r * r;
  3365. this.g = g * g;
  3366. this.b = b * b;
  3367. return this;
  3368. },
  3369. convertLinearToGamma: function () {
  3370. this.r = Math.sqrt( this.r );
  3371. this.g = Math.sqrt( this.g );
  3372. this.b = Math.sqrt( this.b );
  3373. return this;
  3374. },
  3375. getHex: function () {
  3376. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3377. },
  3378. getHexString: function () {
  3379. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3380. },
  3381. getHSL: function ( optionalTarget ) {
  3382. // h,s,l ranges are in 0.0 - 1.0
  3383. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3384. var r = this.r, g = this.g, b = this.b;
  3385. var max = Math.max( r, g, b );
  3386. var min = Math.min( r, g, b );
  3387. var hue, saturation;
  3388. var lightness = ( min + max ) / 2.0;
  3389. if ( min === max ) {
  3390. hue = 0;
  3391. saturation = 0;
  3392. } else {
  3393. var delta = max - min;
  3394. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3395. switch ( max ) {
  3396. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3397. case g: hue = ( b - r ) / delta + 2; break;
  3398. case b: hue = ( r - g ) / delta + 4; break;
  3399. }
  3400. hue /= 6;
  3401. }
  3402. hsl.h = hue;
  3403. hsl.s = saturation;
  3404. hsl.l = lightness;
  3405. return hsl;
  3406. },
  3407. getStyle: function () {
  3408. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3409. },
  3410. offsetHSL: function ( h, s, l ) {
  3411. var hsl = this.getHSL();
  3412. hsl.h += h; hsl.s += s; hsl.l += l;
  3413. this.setHSL( hsl.h, hsl.s, hsl.l );
  3414. return this;
  3415. },
  3416. add: function ( color ) {
  3417. this.r += color.r;
  3418. this.g += color.g;
  3419. this.b += color.b;
  3420. return this;
  3421. },
  3422. addColors: function ( color1, color2 ) {
  3423. this.r = color1.r + color2.r;
  3424. this.g = color1.g + color2.g;
  3425. this.b = color1.b + color2.b;
  3426. return this;
  3427. },
  3428. addScalar: function ( s ) {
  3429. this.r += s;
  3430. this.g += s;
  3431. this.b += s;
  3432. return this;
  3433. },
  3434. sub: function( color ) {
  3435. this.r = Math.max( 0, this.r - color.r );
  3436. this.g = Math.max( 0, this.g - color.g );
  3437. this.b = Math.max( 0, this.b - color.b );
  3438. return this;
  3439. },
  3440. multiply: function ( color ) {
  3441. this.r *= color.r;
  3442. this.g *= color.g;
  3443. this.b *= color.b;
  3444. return this;
  3445. },
  3446. multiplyScalar: function ( s ) {
  3447. this.r *= s;
  3448. this.g *= s;
  3449. this.b *= s;
  3450. return this;
  3451. },
  3452. lerp: function ( color, alpha ) {
  3453. this.r += ( color.r - this.r ) * alpha;
  3454. this.g += ( color.g - this.g ) * alpha;
  3455. this.b += ( color.b - this.b ) * alpha;
  3456. return this;
  3457. },
  3458. equals: function ( c ) {
  3459. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3460. },
  3461. fromArray: function ( array, offset ) {
  3462. if ( offset === undefined ) offset = 0;
  3463. this.r = array[ offset ];
  3464. this.g = array[ offset + 1 ];
  3465. this.b = array[ offset + 2 ];
  3466. return this;
  3467. },
  3468. toArray: function ( array, offset ) {
  3469. if ( array === undefined ) array = [];
  3470. if ( offset === undefined ) offset = 0;
  3471. array[ offset ] = this.r;
  3472. array[ offset + 1 ] = this.g;
  3473. array[ offset + 2 ] = this.b;
  3474. return array;
  3475. },
  3476. toJSON: function () {
  3477. return this.getHex();
  3478. }
  3479. };
  3480. exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3481. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3482. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3483. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3484. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3485. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3486. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3487. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3488. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3489. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3490. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3491. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3492. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3493. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3494. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3495. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3496. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3497. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3498. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3499. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3500. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3501. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3502. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3503. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3504. /**
  3505. * Uniforms library for shared webgl shaders
  3506. */
  3507. var UniformsLib = {
  3508. common: {
  3509. diffuse: { value: new Color( 0xeeeeee ) },
  3510. opacity: { value: 1.0 },
  3511. map: { value: null },
  3512. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3513. specularMap: { value: null },
  3514. alphaMap: { value: null },
  3515. envMap: { value: null },
  3516. flipEnvMap: { value: - 1 },
  3517. reflectivity: { value: 1.0 },
  3518. refractionRatio: { value: 0.98 }
  3519. },
  3520. aomap: {
  3521. aoMap: { value: null },
  3522. aoMapIntensity: { value: 1 }
  3523. },
  3524. lightmap: {
  3525. lightMap: { value: null },
  3526. lightMapIntensity: { value: 1 }
  3527. },
  3528. emissivemap: {
  3529. emissiveMap: { value: null }
  3530. },
  3531. bumpmap: {
  3532. bumpMap: { value: null },
  3533. bumpScale: { value: 1 }
  3534. },
  3535. normalmap: {
  3536. normalMap: { value: null },
  3537. normalScale: { value: new Vector2( 1, 1 ) }
  3538. },
  3539. displacementmap: {
  3540. displacementMap: { value: null },
  3541. displacementScale: { value: 1 },
  3542. displacementBias: { value: 0 }
  3543. },
  3544. roughnessmap: {
  3545. roughnessMap: { value: null }
  3546. },
  3547. metalnessmap: {
  3548. metalnessMap: { value: null }
  3549. },
  3550. fog: {
  3551. fogDensity: { value: 0.00025 },
  3552. fogNear: { value: 1 },
  3553. fogFar: { value: 2000 },
  3554. fogColor: { value: new Color( 0xffffff ) }
  3555. },
  3556. lights: {
  3557. ambientLightColor: { value: [] },
  3558. directionalLights: { value: [], properties: {
  3559. direction: {},
  3560. color: {},
  3561. shadow: {},
  3562. shadowBias: {},
  3563. shadowRadius: {},
  3564. shadowMapSize: {}
  3565. } },
  3566. directionalShadowMap: { value: [] },
  3567. directionalShadowMatrix: { value: [] },
  3568. spotLights: { value: [], properties: {
  3569. color: {},
  3570. position: {},
  3571. direction: {},
  3572. distance: {},
  3573. coneCos: {},
  3574. penumbraCos: {},
  3575. decay: {},
  3576. shadow: {},
  3577. shadowBias: {},
  3578. shadowRadius: {},
  3579. shadowMapSize: {}
  3580. } },
  3581. spotShadowMap: { value: [] },
  3582. spotShadowMatrix: { value: [] },
  3583. pointLights: { value: [], properties: {
  3584. color: {},
  3585. position: {},
  3586. decay: {},
  3587. distance: {},
  3588. shadow: {},
  3589. shadowBias: {},
  3590. shadowRadius: {},
  3591. shadowMapSize: {}
  3592. } },
  3593. pointShadowMap: { value: [] },
  3594. pointShadowMatrix: { value: [] },
  3595. hemisphereLights: { value: [], properties: {
  3596. direction: {},
  3597. skyColor: {},
  3598. groundColor: {}
  3599. } }
  3600. },
  3601. points: {
  3602. diffuse: { value: new Color( 0xeeeeee ) },
  3603. opacity: { value: 1.0 },
  3604. size: { value: 1.0 },
  3605. scale: { value: 1.0 },
  3606. map: { value: null },
  3607. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3608. }
  3609. };
  3610. /**
  3611. * @author alteredq / http://alteredqualia.com/
  3612. * @author mrdoob / http://mrdoob.com/
  3613. * @author mikael emtinger / http://gomo.se/
  3614. */
  3615. var ShaderLib = {
  3616. basic: {
  3617. uniforms: exports.UniformsUtils.merge( [
  3618. UniformsLib.common,
  3619. UniformsLib.aomap,
  3620. UniformsLib.fog
  3621. ] ),
  3622. vertexShader: ShaderChunk.meshbasic_vert,
  3623. fragmentShader: ShaderChunk.meshbasic_frag
  3624. },
  3625. lambert: {
  3626. uniforms: exports.UniformsUtils.merge( [
  3627. UniformsLib.common,
  3628. UniformsLib.aomap,
  3629. UniformsLib.lightmap,
  3630. UniformsLib.emissivemap,
  3631. UniformsLib.fog,
  3632. UniformsLib.lights,
  3633. {
  3634. emissive : { value: new Color( 0x000000 ) }
  3635. }
  3636. ] ),
  3637. vertexShader: ShaderChunk.meshlambert_vert,
  3638. fragmentShader: ShaderChunk.meshlambert_frag
  3639. },
  3640. phong: {
  3641. uniforms: exports.UniformsUtils.merge( [
  3642. UniformsLib.common,
  3643. UniformsLib.aomap,
  3644. UniformsLib.lightmap,
  3645. UniformsLib.emissivemap,
  3646. UniformsLib.bumpmap,
  3647. UniformsLib.normalmap,
  3648. UniformsLib.displacementmap,
  3649. UniformsLib.fog,
  3650. UniformsLib.lights,
  3651. {
  3652. emissive : { value: new Color( 0x000000 ) },
  3653. specular : { value: new Color( 0x111111 ) },
  3654. shininess: { value: 30 }
  3655. }
  3656. ] ),
  3657. vertexShader: ShaderChunk.meshphong_vert,
  3658. fragmentShader: ShaderChunk.meshphong_frag
  3659. },
  3660. standard: {
  3661. uniforms: exports.UniformsUtils.merge( [
  3662. UniformsLib.common,
  3663. UniformsLib.aomap,
  3664. UniformsLib.lightmap,
  3665. UniformsLib.emissivemap,
  3666. UniformsLib.bumpmap,
  3667. UniformsLib.normalmap,
  3668. UniformsLib.displacementmap,
  3669. UniformsLib.roughnessmap,
  3670. UniformsLib.metalnessmap,
  3671. UniformsLib.fog,
  3672. UniformsLib.lights,
  3673. {
  3674. emissive : { value: new Color( 0x000000 ) },
  3675. roughness: { value: 0.5 },
  3676. metalness: { value: 0 },
  3677. envMapIntensity : { value: 1 }, // temporary
  3678. }
  3679. ] ),
  3680. vertexShader: ShaderChunk.meshphysical_vert,
  3681. fragmentShader: ShaderChunk.meshphysical_frag
  3682. },
  3683. points: {
  3684. uniforms: exports.UniformsUtils.merge( [
  3685. UniformsLib.points,
  3686. UniformsLib.fog
  3687. ] ),
  3688. vertexShader: ShaderChunk.points_vert,
  3689. fragmentShader: ShaderChunk.points_frag
  3690. },
  3691. dashed: {
  3692. uniforms: exports.UniformsUtils.merge( [
  3693. UniformsLib.common,
  3694. UniformsLib.fog,
  3695. {
  3696. scale : { value: 1 },
  3697. dashSize : { value: 1 },
  3698. totalSize: { value: 2 }
  3699. }
  3700. ] ),
  3701. vertexShader: ShaderChunk.linedashed_vert,
  3702. fragmentShader: ShaderChunk.linedashed_frag
  3703. },
  3704. depth: {
  3705. uniforms: exports.UniformsUtils.merge( [
  3706. UniformsLib.common,
  3707. UniformsLib.displacementmap
  3708. ] ),
  3709. vertexShader: ShaderChunk.depth_vert,
  3710. fragmentShader: ShaderChunk.depth_frag
  3711. },
  3712. normal: {
  3713. uniforms: {
  3714. opacity : { value: 1.0 }
  3715. },
  3716. vertexShader: ShaderChunk.normal_vert,
  3717. fragmentShader: ShaderChunk.normal_frag
  3718. },
  3719. /* -------------------------------------------------------------------------
  3720. // Cube map shader
  3721. ------------------------------------------------------------------------- */
  3722. cube: {
  3723. uniforms: {
  3724. tCube: { value: null },
  3725. tFlip: { value: - 1 },
  3726. opacity: { value: 1.0 }
  3727. },
  3728. vertexShader: ShaderChunk.cube_vert,
  3729. fragmentShader: ShaderChunk.cube_frag
  3730. },
  3731. /* -------------------------------------------------------------------------
  3732. // Cube map shader
  3733. ------------------------------------------------------------------------- */
  3734. equirect: {
  3735. uniforms: {
  3736. tEquirect: { value: null },
  3737. tFlip: { value: - 1 }
  3738. },
  3739. vertexShader: ShaderChunk.equirect_vert,
  3740. fragmentShader: ShaderChunk.equirect_frag
  3741. },
  3742. distanceRGBA: {
  3743. uniforms: {
  3744. lightPos: { value: new Vector3() }
  3745. },
  3746. vertexShader: ShaderChunk.distanceRGBA_vert,
  3747. fragmentShader: ShaderChunk.distanceRGBA_frag
  3748. }
  3749. };
  3750. ShaderLib.physical = {
  3751. uniforms: exports.UniformsUtils.merge( [
  3752. ShaderLib.standard.uniforms,
  3753. {
  3754. clearCoat: { value: 0 },
  3755. clearCoatRoughness: { value: 0 }
  3756. }
  3757. ] ),
  3758. vertexShader: ShaderChunk.meshphysical_vert,
  3759. fragmentShader: ShaderChunk.meshphysical_frag
  3760. };
  3761. /**
  3762. * @author bhouston / http://clara.io
  3763. */
  3764. function Box2( min, max ) {
  3765. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3766. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3767. }
  3768. Box2.prototype = {
  3769. constructor: Box2,
  3770. set: function ( min, max ) {
  3771. this.min.copy( min );
  3772. this.max.copy( max );
  3773. return this;
  3774. },
  3775. setFromPoints: function ( points ) {
  3776. this.makeEmpty();
  3777. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3778. this.expandByPoint( points[ i ] );
  3779. }
  3780. return this;
  3781. },
  3782. setFromCenterAndSize: function () {
  3783. var v1 = new Vector2();
  3784. return function setFromCenterAndSize( center, size ) {
  3785. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3786. this.min.copy( center ).sub( halfSize );
  3787. this.max.copy( center ).add( halfSize );
  3788. return this;
  3789. };
  3790. }(),
  3791. clone: function () {
  3792. return new this.constructor().copy( this );
  3793. },
  3794. copy: function ( box ) {
  3795. this.min.copy( box.min );
  3796. this.max.copy( box.max );
  3797. return this;
  3798. },
  3799. makeEmpty: function () {
  3800. this.min.x = this.min.y = + Infinity;
  3801. this.max.x = this.max.y = - Infinity;
  3802. return this;
  3803. },
  3804. isEmpty: function () {
  3805. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3806. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3807. },
  3808. center: function ( optionalTarget ) {
  3809. var result = optionalTarget || new Vector2();
  3810. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3811. },
  3812. size: function ( optionalTarget ) {
  3813. var result = optionalTarget || new Vector2();
  3814. return result.subVectors( this.max, this.min );
  3815. },
  3816. expandByPoint: function ( point ) {
  3817. this.min.min( point );
  3818. this.max.max( point );
  3819. return this;
  3820. },
  3821. expandByVector: function ( vector ) {
  3822. this.min.sub( vector );
  3823. this.max.add( vector );
  3824. return this;
  3825. },
  3826. expandByScalar: function ( scalar ) {
  3827. this.min.addScalar( - scalar );
  3828. this.max.addScalar( scalar );
  3829. return this;
  3830. },
  3831. containsPoint: function ( point ) {
  3832. if ( point.x < this.min.x || point.x > this.max.x ||
  3833. point.y < this.min.y || point.y > this.max.y ) {
  3834. return false;
  3835. }
  3836. return true;
  3837. },
  3838. containsBox: function ( box ) {
  3839. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  3840. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  3841. return true;
  3842. }
  3843. return false;
  3844. },
  3845. getParameter: function ( point, optionalTarget ) {
  3846. // This can potentially have a divide by zero if the box
  3847. // has a size dimension of 0.
  3848. var result = optionalTarget || new Vector2();
  3849. return result.set(
  3850. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3851. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3852. );
  3853. },
  3854. intersectsBox: function ( box ) {
  3855. // using 6 splitting planes to rule out intersections.
  3856. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  3857. box.max.y < this.min.y || box.min.y > this.max.y ) {
  3858. return false;
  3859. }
  3860. return true;
  3861. },
  3862. clampPoint: function ( point, optionalTarget ) {
  3863. var result = optionalTarget || new Vector2();
  3864. return result.copy( point ).clamp( this.min, this.max );
  3865. },
  3866. distanceToPoint: function () {
  3867. var v1 = new Vector2();
  3868. return function distanceToPoint( point ) {
  3869. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3870. return clampedPoint.sub( point ).length();
  3871. };
  3872. }(),
  3873. intersect: function ( box ) {
  3874. this.min.max( box.min );
  3875. this.max.min( box.max );
  3876. return this;
  3877. },
  3878. union: function ( box ) {
  3879. this.min.min( box.min );
  3880. this.max.max( box.max );
  3881. return this;
  3882. },
  3883. translate: function ( offset ) {
  3884. this.min.add( offset );
  3885. this.max.add( offset );
  3886. return this;
  3887. },
  3888. equals: function ( box ) {
  3889. return box.min.equals( this.min ) && box.max.equals( this.max );
  3890. }
  3891. };
  3892. /**
  3893. * @author mikael emtinger / http://gomo.se/
  3894. * @author alteredq / http://alteredqualia.com/
  3895. */
  3896. function LensFlarePlugin( renderer, flares ) {
  3897. var gl = renderer.context;
  3898. var state = renderer.state;
  3899. var vertexBuffer, elementBuffer;
  3900. var shader, program, attributes, uniforms;
  3901. var tempTexture, occlusionTexture;
  3902. function init() {
  3903. var vertices = new Float32Array( [
  3904. - 1, - 1, 0, 0,
  3905. 1, - 1, 1, 0,
  3906. 1, 1, 1, 1,
  3907. - 1, 1, 0, 1
  3908. ] );
  3909. var faces = new Uint16Array( [
  3910. 0, 1, 2,
  3911. 0, 2, 3
  3912. ] );
  3913. // buffers
  3914. vertexBuffer = gl.createBuffer();
  3915. elementBuffer = gl.createBuffer();
  3916. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3917. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3918. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3919. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3920. // textures
  3921. tempTexture = gl.createTexture();
  3922. occlusionTexture = gl.createTexture();
  3923. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3924. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3925. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3926. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3927. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3928. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3929. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3930. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3931. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3932. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3933. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3934. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3935. shader = {
  3936. vertexShader: [
  3937. "uniform lowp int renderType;",
  3938. "uniform vec3 screenPosition;",
  3939. "uniform vec2 scale;",
  3940. "uniform float rotation;",
  3941. "uniform sampler2D occlusionMap;",
  3942. "attribute vec2 position;",
  3943. "attribute vec2 uv;",
  3944. "varying vec2 vUV;",
  3945. "varying float vVisibility;",
  3946. "void main() {",
  3947. "vUV = uv;",
  3948. "vec2 pos = position;",
  3949. "if ( renderType == 2 ) {",
  3950. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3951. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3952. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3953. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3954. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3955. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3956. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3957. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3958. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3959. "vVisibility = visibility.r / 9.0;",
  3960. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3961. "vVisibility *= visibility.b / 9.0;",
  3962. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3963. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3964. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3965. "}",
  3966. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3967. "}"
  3968. ].join( "\n" ),
  3969. fragmentShader: [
  3970. "uniform lowp int renderType;",
  3971. "uniform sampler2D map;",
  3972. "uniform float opacity;",
  3973. "uniform vec3 color;",
  3974. "varying vec2 vUV;",
  3975. "varying float vVisibility;",
  3976. "void main() {",
  3977. // pink square
  3978. "if ( renderType == 0 ) {",
  3979. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  3980. // restore
  3981. "} else if ( renderType == 1 ) {",
  3982. "gl_FragColor = texture2D( map, vUV );",
  3983. // flare
  3984. "} else {",
  3985. "vec4 texture = texture2D( map, vUV );",
  3986. "texture.a *= opacity * vVisibility;",
  3987. "gl_FragColor = texture;",
  3988. "gl_FragColor.rgb *= color;",
  3989. "}",
  3990. "}"
  3991. ].join( "\n" )
  3992. };
  3993. program = createProgram( shader );
  3994. attributes = {
  3995. vertex: gl.getAttribLocation ( program, "position" ),
  3996. uv: gl.getAttribLocation ( program, "uv" )
  3997. };
  3998. uniforms = {
  3999. renderType: gl.getUniformLocation( program, "renderType" ),
  4000. map: gl.getUniformLocation( program, "map" ),
  4001. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4002. opacity: gl.getUniformLocation( program, "opacity" ),
  4003. color: gl.getUniformLocation( program, "color" ),
  4004. scale: gl.getUniformLocation( program, "scale" ),
  4005. rotation: gl.getUniformLocation( program, "rotation" ),
  4006. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4007. };
  4008. }
  4009. /*
  4010. * Render lens flares
  4011. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4012. * reads these back and calculates occlusion.
  4013. */
  4014. this.render = function ( scene, camera, viewport ) {
  4015. if ( flares.length === 0 ) return;
  4016. var tempPosition = new Vector3();
  4017. var invAspect = viewport.w / viewport.z,
  4018. halfViewportWidth = viewport.z * 0.5,
  4019. halfViewportHeight = viewport.w * 0.5;
  4020. var size = 16 / viewport.w,
  4021. scale = new Vector2( size * invAspect, size );
  4022. var screenPosition = new Vector3( 1, 1, 0 ),
  4023. screenPositionPixels = new Vector2( 1, 1 );
  4024. var validArea = new Box2();
  4025. validArea.min.set( 0, 0 );
  4026. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  4027. if ( program === undefined ) {
  4028. init();
  4029. }
  4030. gl.useProgram( program );
  4031. state.initAttributes();
  4032. state.enableAttribute( attributes.vertex );
  4033. state.enableAttribute( attributes.uv );
  4034. state.disableUnusedAttributes();
  4035. // loop through all lens flares to update their occlusion and positions
  4036. // setup gl and common used attribs/uniforms
  4037. gl.uniform1i( uniforms.occlusionMap, 0 );
  4038. gl.uniform1i( uniforms.map, 1 );
  4039. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4040. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4041. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4042. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4043. state.disable( gl.CULL_FACE );
  4044. state.setDepthWrite( false );
  4045. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4046. size = 16 / viewport.w;
  4047. scale.set( size * invAspect, size );
  4048. // calc object screen position
  4049. var flare = flares[ i ];
  4050. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4051. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4052. tempPosition.applyProjection( camera.projectionMatrix );
  4053. // setup arrays for gl programs
  4054. screenPosition.copy( tempPosition );
  4055. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4056. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4057. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4058. // screen cull
  4059. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4060. // save current RGB to temp texture
  4061. state.activeTexture( gl.TEXTURE0 );
  4062. state.bindTexture( gl.TEXTURE_2D, null );
  4063. state.activeTexture( gl.TEXTURE1 );
  4064. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4065. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4066. // render pink quad
  4067. gl.uniform1i( uniforms.renderType, 0 );
  4068. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4069. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4070. state.disable( gl.BLEND );
  4071. state.enable( gl.DEPTH_TEST );
  4072. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4073. // copy result to occlusionMap
  4074. state.activeTexture( gl.TEXTURE0 );
  4075. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4076. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4077. // restore graphics
  4078. gl.uniform1i( uniforms.renderType, 1 );
  4079. state.disable( gl.DEPTH_TEST );
  4080. state.activeTexture( gl.TEXTURE1 );
  4081. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4082. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4083. // update object positions
  4084. flare.positionScreen.copy( screenPosition );
  4085. if ( flare.customUpdateCallback ) {
  4086. flare.customUpdateCallback( flare );
  4087. } else {
  4088. flare.updateLensFlares();
  4089. }
  4090. // render flares
  4091. gl.uniform1i( uniforms.renderType, 2 );
  4092. state.enable( gl.BLEND );
  4093. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4094. var sprite = flare.lensFlares[ j ];
  4095. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4096. screenPosition.x = sprite.x;
  4097. screenPosition.y = sprite.y;
  4098. screenPosition.z = sprite.z;
  4099. size = sprite.size * sprite.scale / viewport.w;
  4100. scale.x = size * invAspect;
  4101. scale.y = size;
  4102. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4103. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4104. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4105. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4106. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4107. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4108. renderer.setTexture2D( sprite.texture, 1 );
  4109. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4110. }
  4111. }
  4112. }
  4113. }
  4114. // restore gl
  4115. state.enable( gl.CULL_FACE );
  4116. state.enable( gl.DEPTH_TEST );
  4117. state.setDepthWrite( true );
  4118. renderer.resetGLState();
  4119. };
  4120. function createProgram( shader ) {
  4121. var program = gl.createProgram();
  4122. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4123. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4124. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4125. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4126. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4127. gl.compileShader( fragmentShader );
  4128. gl.compileShader( vertexShader );
  4129. gl.attachShader( program, fragmentShader );
  4130. gl.attachShader( program, vertexShader );
  4131. gl.linkProgram( program );
  4132. return program;
  4133. }
  4134. }
  4135. /**
  4136. * @author mikael emtinger / http://gomo.se/
  4137. * @author alteredq / http://alteredqualia.com/
  4138. */
  4139. function SpritePlugin( renderer, sprites ) {
  4140. var gl = renderer.context;
  4141. var state = renderer.state;
  4142. var vertexBuffer, elementBuffer;
  4143. var program, attributes, uniforms;
  4144. var texture;
  4145. // decompose matrixWorld
  4146. var spritePosition = new Vector3();
  4147. var spriteRotation = new Quaternion();
  4148. var spriteScale = new Vector3();
  4149. function init() {
  4150. var vertices = new Float32Array( [
  4151. - 0.5, - 0.5, 0, 0,
  4152. 0.5, - 0.5, 1, 0,
  4153. 0.5, 0.5, 1, 1,
  4154. - 0.5, 0.5, 0, 1
  4155. ] );
  4156. var faces = new Uint16Array( [
  4157. 0, 1, 2,
  4158. 0, 2, 3
  4159. ] );
  4160. vertexBuffer = gl.createBuffer();
  4161. elementBuffer = gl.createBuffer();
  4162. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4163. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4164. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4165. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4166. program = createProgram();
  4167. attributes = {
  4168. position: gl.getAttribLocation ( program, 'position' ),
  4169. uv: gl.getAttribLocation ( program, 'uv' )
  4170. };
  4171. uniforms = {
  4172. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4173. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4174. rotation: gl.getUniformLocation( program, 'rotation' ),
  4175. scale: gl.getUniformLocation( program, 'scale' ),
  4176. color: gl.getUniformLocation( program, 'color' ),
  4177. map: gl.getUniformLocation( program, 'map' ),
  4178. opacity: gl.getUniformLocation( program, 'opacity' ),
  4179. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4180. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4181. fogType: gl.getUniformLocation( program, 'fogType' ),
  4182. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4183. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4184. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4185. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4186. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4187. };
  4188. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4189. canvas.width = 8;
  4190. canvas.height = 8;
  4191. var context = canvas.getContext( '2d' );
  4192. context.fillStyle = 'white';
  4193. context.fillRect( 0, 0, 8, 8 );
  4194. texture = new Texture( canvas );
  4195. texture.needsUpdate = true;
  4196. }
  4197. this.render = function ( scene, camera ) {
  4198. if ( sprites.length === 0 ) return;
  4199. // setup gl
  4200. if ( program === undefined ) {
  4201. init();
  4202. }
  4203. gl.useProgram( program );
  4204. state.initAttributes();
  4205. state.enableAttribute( attributes.position );
  4206. state.enableAttribute( attributes.uv );
  4207. state.disableUnusedAttributes();
  4208. state.disable( gl.CULL_FACE );
  4209. state.enable( gl.BLEND );
  4210. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4211. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4212. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4213. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4214. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4215. state.activeTexture( gl.TEXTURE0 );
  4216. gl.uniform1i( uniforms.map, 0 );
  4217. var oldFogType = 0;
  4218. var sceneFogType = 0;
  4219. var fog = scene.fog;
  4220. if ( fog ) {
  4221. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4222. if ( (fog && fog.isFog) ) {
  4223. gl.uniform1f( uniforms.fogNear, fog.near );
  4224. gl.uniform1f( uniforms.fogFar, fog.far );
  4225. gl.uniform1i( uniforms.fogType, 1 );
  4226. oldFogType = 1;
  4227. sceneFogType = 1;
  4228. } else if ( (fog && fog.isFogExp2) ) {
  4229. gl.uniform1f( uniforms.fogDensity, fog.density );
  4230. gl.uniform1i( uniforms.fogType, 2 );
  4231. oldFogType = 2;
  4232. sceneFogType = 2;
  4233. }
  4234. } else {
  4235. gl.uniform1i( uniforms.fogType, 0 );
  4236. oldFogType = 0;
  4237. sceneFogType = 0;
  4238. }
  4239. // update positions and sort
  4240. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4241. var sprite = sprites[ i ];
  4242. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4243. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4244. }
  4245. sprites.sort( painterSortStable );
  4246. // render all sprites
  4247. var scale = [];
  4248. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4249. var sprite = sprites[ i ];
  4250. var material = sprite.material;
  4251. if ( material.visible === false ) continue;
  4252. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4253. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4254. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4255. scale[ 0 ] = spriteScale.x;
  4256. scale[ 1 ] = spriteScale.y;
  4257. var fogType = 0;
  4258. if ( scene.fog && material.fog ) {
  4259. fogType = sceneFogType;
  4260. }
  4261. if ( oldFogType !== fogType ) {
  4262. gl.uniform1i( uniforms.fogType, fogType );
  4263. oldFogType = fogType;
  4264. }
  4265. if ( material.map !== null ) {
  4266. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4267. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4268. } else {
  4269. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4270. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4271. }
  4272. gl.uniform1f( uniforms.opacity, material.opacity );
  4273. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4274. gl.uniform1f( uniforms.rotation, material.rotation );
  4275. gl.uniform2fv( uniforms.scale, scale );
  4276. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4277. state.setDepthTest( material.depthTest );
  4278. state.setDepthWrite( material.depthWrite );
  4279. if ( material.map ) {
  4280. renderer.setTexture2D( material.map, 0 );
  4281. } else {
  4282. renderer.setTexture2D( texture, 0 );
  4283. }
  4284. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4285. }
  4286. // restore gl
  4287. state.enable( gl.CULL_FACE );
  4288. renderer.resetGLState();
  4289. };
  4290. function createProgram() {
  4291. var program = gl.createProgram();
  4292. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4293. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4294. gl.shaderSource( vertexShader, [
  4295. 'precision ' + renderer.getPrecision() + ' float;',
  4296. 'uniform mat4 modelViewMatrix;',
  4297. 'uniform mat4 projectionMatrix;',
  4298. 'uniform float rotation;',
  4299. 'uniform vec2 scale;',
  4300. 'uniform vec2 uvOffset;',
  4301. 'uniform vec2 uvScale;',
  4302. 'attribute vec2 position;',
  4303. 'attribute vec2 uv;',
  4304. 'varying vec2 vUV;',
  4305. 'void main() {',
  4306. 'vUV = uvOffset + uv * uvScale;',
  4307. 'vec2 alignedPosition = position * scale;',
  4308. 'vec2 rotatedPosition;',
  4309. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4310. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4311. 'vec4 finalPosition;',
  4312. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4313. 'finalPosition.xy += rotatedPosition;',
  4314. 'finalPosition = projectionMatrix * finalPosition;',
  4315. 'gl_Position = finalPosition;',
  4316. '}'
  4317. ].join( '\n' ) );
  4318. gl.shaderSource( fragmentShader, [
  4319. 'precision ' + renderer.getPrecision() + ' float;',
  4320. 'uniform vec3 color;',
  4321. 'uniform sampler2D map;',
  4322. 'uniform float opacity;',
  4323. 'uniform int fogType;',
  4324. 'uniform vec3 fogColor;',
  4325. 'uniform float fogDensity;',
  4326. 'uniform float fogNear;',
  4327. 'uniform float fogFar;',
  4328. 'uniform float alphaTest;',
  4329. 'varying vec2 vUV;',
  4330. 'void main() {',
  4331. 'vec4 texture = texture2D( map, vUV );',
  4332. 'if ( texture.a < alphaTest ) discard;',
  4333. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4334. 'if ( fogType > 0 ) {',
  4335. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4336. 'float fogFactor = 0.0;',
  4337. 'if ( fogType == 1 ) {',
  4338. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4339. '} else {',
  4340. 'const float LOG2 = 1.442695;',
  4341. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4342. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4343. '}',
  4344. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4345. '}',
  4346. '}'
  4347. ].join( '\n' ) );
  4348. gl.compileShader( vertexShader );
  4349. gl.compileShader( fragmentShader );
  4350. gl.attachShader( program, vertexShader );
  4351. gl.attachShader( program, fragmentShader );
  4352. gl.linkProgram( program );
  4353. return program;
  4354. }
  4355. function painterSortStable( a, b ) {
  4356. if ( a.renderOrder !== b.renderOrder ) {
  4357. return a.renderOrder - b.renderOrder;
  4358. } else if ( a.z !== b.z ) {
  4359. return b.z - a.z;
  4360. } else {
  4361. return b.id - a.id;
  4362. }
  4363. }
  4364. }
  4365. /**
  4366. * @author mrdoob / http://mrdoob.com/
  4367. * @author alteredq / http://alteredqualia.com/
  4368. */
  4369. function Material() {
  4370. Object.defineProperty( this, 'id', { value: MaterialIdCount() } );
  4371. this.uuid = exports.Math.generateUUID();
  4372. this.name = '';
  4373. this.type = 'Material';
  4374. this.fog = true;
  4375. this.lights = true;
  4376. this.blending = NormalBlending;
  4377. this.side = FrontSide;
  4378. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4379. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4380. this.opacity = 1;
  4381. this.transparent = false;
  4382. this.blendSrc = SrcAlphaFactor;
  4383. this.blendDst = OneMinusSrcAlphaFactor;
  4384. this.blendEquation = AddEquation;
  4385. this.blendSrcAlpha = null;
  4386. this.blendDstAlpha = null;
  4387. this.blendEquationAlpha = null;
  4388. this.depthFunc = LessEqualDepth;
  4389. this.depthTest = true;
  4390. this.depthWrite = true;
  4391. this.clippingPlanes = null;
  4392. this.clipShadows = false;
  4393. this.colorWrite = true;
  4394. this.precision = null; // override the renderer's default precision for this material
  4395. this.polygonOffset = false;
  4396. this.polygonOffsetFactor = 0;
  4397. this.polygonOffsetUnits = 0;
  4398. this.alphaTest = 0;
  4399. this.premultipliedAlpha = false;
  4400. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4401. this.visible = true;
  4402. this._needsUpdate = true;
  4403. }
  4404. Material.prototype = {
  4405. constructor: Material,
  4406. isMaterial: true,
  4407. get needsUpdate() {
  4408. return this._needsUpdate;
  4409. },
  4410. set needsUpdate( value ) {
  4411. if ( value === true ) this.update();
  4412. this._needsUpdate = value;
  4413. },
  4414. setValues: function ( values ) {
  4415. if ( values === undefined ) return;
  4416. for ( var key in values ) {
  4417. var newValue = values[ key ];
  4418. if ( newValue === undefined ) {
  4419. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4420. continue;
  4421. }
  4422. var currentValue = this[ key ];
  4423. if ( currentValue === undefined ) {
  4424. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4425. continue;
  4426. }
  4427. if ( (currentValue && currentValue.isColor) ) {
  4428. currentValue.set( newValue );
  4429. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4430. currentValue.copy( newValue );
  4431. } else if ( key === 'overdraw' ) {
  4432. // ensure overdraw is backwards-compatible with legacy boolean type
  4433. this[ key ] = Number( newValue );
  4434. } else {
  4435. this[ key ] = newValue;
  4436. }
  4437. }
  4438. },
  4439. toJSON: function ( meta ) {
  4440. var isRoot = meta === undefined;
  4441. if ( isRoot ) {
  4442. meta = {
  4443. textures: {},
  4444. images: {}
  4445. };
  4446. }
  4447. var data = {
  4448. metadata: {
  4449. version: 4.4,
  4450. type: 'Material',
  4451. generator: 'Material.toJSON'
  4452. }
  4453. };
  4454. // standard Material serialization
  4455. data.uuid = this.uuid;
  4456. data.type = this.type;
  4457. if ( this.name !== '' ) data.name = this.name;
  4458. if ( (this.color && this.color.isColor) ) data.color = this.color.getHex();
  4459. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4460. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4461. if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex();
  4462. if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex();
  4463. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4464. if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid;
  4465. if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4466. if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4467. if ( (this.bumpMap && this.bumpMap.isTexture) ) {
  4468. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4469. data.bumpScale = this.bumpScale;
  4470. }
  4471. if ( (this.normalMap && this.normalMap.isTexture) ) {
  4472. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4473. data.normalScale = this.normalScale.toArray();
  4474. }
  4475. if ( (this.displacementMap && this.displacementMap.isTexture) ) {
  4476. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4477. data.displacementScale = this.displacementScale;
  4478. data.displacementBias = this.displacementBias;
  4479. }
  4480. if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4481. if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4482. if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4483. if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4484. if ( (this.envMap && this.envMap.isTexture) ) {
  4485. data.envMap = this.envMap.toJSON( meta ).uuid;
  4486. data.reflectivity = this.reflectivity; // Scale behind envMap
  4487. }
  4488. if ( this.size !== undefined ) data.size = this.size;
  4489. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4490. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4491. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4492. if ( this.side !== FrontSide ) data.side = this.side;
  4493. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4494. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4495. if ( this.transparent === true ) data.transparent = this.transparent;
  4496. data.depthFunc = this.depthFunc;
  4497. data.depthTest = this.depthTest;
  4498. data.depthWrite = this.depthWrite;
  4499. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4500. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4501. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4502. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4503. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4504. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4505. data.skinning = this.skinning;
  4506. data.morphTargets = this.morphTargets;
  4507. // TODO: Copied from Object3D.toJSON
  4508. function extractFromCache( cache ) {
  4509. var values = [];
  4510. for ( var key in cache ) {
  4511. var data = cache[ key ];
  4512. delete data.metadata;
  4513. values.push( data );
  4514. }
  4515. return values;
  4516. }
  4517. if ( isRoot ) {
  4518. var textures = extractFromCache( meta.textures );
  4519. var images = extractFromCache( meta.images );
  4520. if ( textures.length > 0 ) data.textures = textures;
  4521. if ( images.length > 0 ) data.images = images;
  4522. }
  4523. return data;
  4524. },
  4525. clone: function () {
  4526. return new this.constructor().copy( this );
  4527. },
  4528. copy: function ( source ) {
  4529. this.name = source.name;
  4530. this.fog = source.fog;
  4531. this.lights = source.lights;
  4532. this.blending = source.blending;
  4533. this.side = source.side;
  4534. this.shading = source.shading;
  4535. this.vertexColors = source.vertexColors;
  4536. this.opacity = source.opacity;
  4537. this.transparent = source.transparent;
  4538. this.blendSrc = source.blendSrc;
  4539. this.blendDst = source.blendDst;
  4540. this.blendEquation = source.blendEquation;
  4541. this.blendSrcAlpha = source.blendSrcAlpha;
  4542. this.blendDstAlpha = source.blendDstAlpha;
  4543. this.blendEquationAlpha = source.blendEquationAlpha;
  4544. this.depthFunc = source.depthFunc;
  4545. this.depthTest = source.depthTest;
  4546. this.depthWrite = source.depthWrite;
  4547. this.colorWrite = source.colorWrite;
  4548. this.precision = source.precision;
  4549. this.polygonOffset = source.polygonOffset;
  4550. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4551. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4552. this.alphaTest = source.alphaTest;
  4553. this.premultipliedAlpha = source.premultipliedAlpha;
  4554. this.overdraw = source.overdraw;
  4555. this.visible = source.visible;
  4556. this.clipShadows = source.clipShadows;
  4557. var srcPlanes = source.clippingPlanes,
  4558. dstPlanes = null;
  4559. if ( srcPlanes !== null ) {
  4560. var n = srcPlanes.length;
  4561. dstPlanes = new Array( n );
  4562. for ( var i = 0; i !== n; ++ i )
  4563. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4564. }
  4565. this.clippingPlanes = dstPlanes;
  4566. return this;
  4567. },
  4568. update: function () {
  4569. this.dispatchEvent( { type: 'update' } );
  4570. },
  4571. dispose: function () {
  4572. this.dispatchEvent( { type: 'dispose' } );
  4573. }
  4574. };
  4575. Object.assign( Material.prototype, EventDispatcher.prototype );
  4576. var count$1 = 0;
  4577. function MaterialIdCount() { return count$1++; };
  4578. /**
  4579. * @author alteredq / http://alteredqualia.com/
  4580. *
  4581. * parameters = {
  4582. * defines: { "label" : "value" },
  4583. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4584. *
  4585. * fragmentShader: <string>,
  4586. * vertexShader: <string>,
  4587. *
  4588. * wireframe: <boolean>,
  4589. * wireframeLinewidth: <float>,
  4590. *
  4591. * lights: <bool>,
  4592. *
  4593. * skinning: <bool>,
  4594. * morphTargets: <bool>,
  4595. * morphNormals: <bool>
  4596. * }
  4597. */
  4598. function ShaderMaterial( parameters ) {
  4599. Material.call( this );
  4600. this.type = 'ShaderMaterial';
  4601. this.defines = {};
  4602. this.uniforms = {};
  4603. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4604. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4605. this.linewidth = 1;
  4606. this.wireframe = false;
  4607. this.wireframeLinewidth = 1;
  4608. this.fog = false; // set to use scene fog
  4609. this.lights = false; // set to use scene lights
  4610. this.clipping = false; // set to use user-defined clipping planes
  4611. this.skinning = false; // set to use skinning attribute streams
  4612. this.morphTargets = false; // set to use morph targets
  4613. this.morphNormals = false; // set to use morph normals
  4614. this.extensions = {
  4615. derivatives: false, // set to use derivatives
  4616. fragDepth: false, // set to use fragment depth values
  4617. drawBuffers: false, // set to use draw buffers
  4618. shaderTextureLOD: false // set to use shader texture LOD
  4619. };
  4620. // When rendered geometry doesn't include these attributes but the material does,
  4621. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4622. this.defaultAttributeValues = {
  4623. 'color': [ 1, 1, 1 ],
  4624. 'uv': [ 0, 0 ],
  4625. 'uv2': [ 0, 0 ]
  4626. };
  4627. this.index0AttributeName = undefined;
  4628. if ( parameters !== undefined ) {
  4629. if ( parameters.attributes !== undefined ) {
  4630. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4631. }
  4632. this.setValues( parameters );
  4633. }
  4634. }
  4635. ShaderMaterial.prototype = Object.create( Material.prototype );
  4636. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4637. ShaderMaterial.prototype.isShaderMaterial = true;
  4638. ShaderMaterial.prototype.copy = function ( source ) {
  4639. Material.prototype.copy.call( this, source );
  4640. this.fragmentShader = source.fragmentShader;
  4641. this.vertexShader = source.vertexShader;
  4642. this.uniforms = exports.UniformsUtils.clone( source.uniforms );
  4643. this.defines = source.defines;
  4644. this.wireframe = source.wireframe;
  4645. this.wireframeLinewidth = source.wireframeLinewidth;
  4646. this.lights = source.lights;
  4647. this.clipping = source.clipping;
  4648. this.skinning = source.skinning;
  4649. this.morphTargets = source.morphTargets;
  4650. this.morphNormals = source.morphNormals;
  4651. this.extensions = source.extensions;
  4652. return this;
  4653. };
  4654. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4655. var data = Material.prototype.toJSON.call( this, meta );
  4656. data.uniforms = this.uniforms;
  4657. data.vertexShader = this.vertexShader;
  4658. data.fragmentShader = this.fragmentShader;
  4659. return data;
  4660. };
  4661. /**
  4662. * @author mrdoob / http://mrdoob.com/
  4663. * @author alteredq / http://alteredqualia.com/
  4664. * @author bhouston / https://clara.io
  4665. * @author WestLangley / http://github.com/WestLangley
  4666. *
  4667. * parameters = {
  4668. *
  4669. * opacity: <float>,
  4670. *
  4671. * map: new THREE.Texture( <Image> ),
  4672. *
  4673. * alphaMap: new THREE.Texture( <Image> ),
  4674. *
  4675. * displacementMap: new THREE.Texture( <Image> ),
  4676. * displacementScale: <float>,
  4677. * displacementBias: <float>,
  4678. *
  4679. * wireframe: <boolean>,
  4680. * wireframeLinewidth: <float>
  4681. * }
  4682. */
  4683. function MeshDepthMaterial( parameters ) {
  4684. Material.call( this );
  4685. this.type = 'MeshDepthMaterial';
  4686. this.depthPacking = BasicDepthPacking;
  4687. this.skinning = false;
  4688. this.morphTargets = false;
  4689. this.map = null;
  4690. this.alphaMap = null;
  4691. this.displacementMap = null;
  4692. this.displacementScale = 1;
  4693. this.displacementBias = 0;
  4694. this.wireframe = false;
  4695. this.wireframeLinewidth = 1;
  4696. this.fog = false;
  4697. this.lights = false;
  4698. this.setValues( parameters );
  4699. }
  4700. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4701. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4702. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4703. MeshDepthMaterial.prototype.copy = function ( source ) {
  4704. Material.prototype.copy.call( this, source );
  4705. this.depthPacking = source.depthPacking;
  4706. this.skinning = source.skinning;
  4707. this.morphTargets = source.morphTargets;
  4708. this.map = source.map;
  4709. this.alphaMap = source.alphaMap;
  4710. this.displacementMap = source.displacementMap;
  4711. this.displacementScale = source.displacementScale;
  4712. this.displacementBias = source.displacementBias;
  4713. this.wireframe = source.wireframe;
  4714. this.wireframeLinewidth = source.wireframeLinewidth;
  4715. return this;
  4716. };
  4717. /**
  4718. * @author bhouston / http://clara.io
  4719. * @author WestLangley / http://github.com/WestLangley
  4720. */
  4721. function Box3( min, max ) {
  4722. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4723. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4724. }
  4725. Box3.prototype = {
  4726. constructor: Box3,
  4727. isBox3: true,
  4728. set: function ( min, max ) {
  4729. this.min.copy( min );
  4730. this.max.copy( max );
  4731. return this;
  4732. },
  4733. setFromArray: function ( array ) {
  4734. var minX = + Infinity;
  4735. var minY = + Infinity;
  4736. var minZ = + Infinity;
  4737. var maxX = - Infinity;
  4738. var maxY = - Infinity;
  4739. var maxZ = - Infinity;
  4740. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4741. var x = array[ i ];
  4742. var y = array[ i + 1 ];
  4743. var z = array[ i + 2 ];
  4744. if ( x < minX ) minX = x;
  4745. if ( y < minY ) minY = y;
  4746. if ( z < minZ ) minZ = z;
  4747. if ( x > maxX ) maxX = x;
  4748. if ( y > maxY ) maxY = y;
  4749. if ( z > maxZ ) maxZ = z;
  4750. }
  4751. this.min.set( minX, minY, minZ );
  4752. this.max.set( maxX, maxY, maxZ );
  4753. },
  4754. setFromPoints: function ( points ) {
  4755. this.makeEmpty();
  4756. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4757. this.expandByPoint( points[ i ] );
  4758. }
  4759. return this;
  4760. },
  4761. setFromCenterAndSize: function () {
  4762. var v1 = new Vector3();
  4763. return function setFromCenterAndSize( center, size ) {
  4764. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4765. this.min.copy( center ).sub( halfSize );
  4766. this.max.copy( center ).add( halfSize );
  4767. return this;
  4768. };
  4769. }(),
  4770. setFromObject: function () {
  4771. // Computes the world-axis-aligned bounding box of an object (including its children),
  4772. // accounting for both the object's, and children's, world transforms
  4773. var v1 = new Vector3();
  4774. return function setFromObject( object ) {
  4775. var scope = this;
  4776. object.updateMatrixWorld( true );
  4777. this.makeEmpty();
  4778. object.traverse( function ( node ) {
  4779. var geometry = node.geometry;
  4780. if ( geometry !== undefined ) {
  4781. if ( (geometry && geometry.isGeometry) ) {
  4782. var vertices = geometry.vertices;
  4783. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4784. v1.copy( vertices[ i ] );
  4785. v1.applyMatrix4( node.matrixWorld );
  4786. scope.expandByPoint( v1 );
  4787. }
  4788. } else if ( (geometry && geometry.isBufferGeometry) ) {
  4789. var attribute = geometry.attributes.position;
  4790. if ( attribute !== undefined ) {
  4791. var array, offset, stride;
  4792. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  4793. array = attribute.data.array;
  4794. offset = attribute.offset;
  4795. stride = attribute.data.stride;
  4796. } else {
  4797. array = attribute.array;
  4798. offset = 0;
  4799. stride = 3;
  4800. }
  4801. for ( var i = offset, il = array.length; i < il; i += stride ) {
  4802. v1.fromArray( array, i );
  4803. v1.applyMatrix4( node.matrixWorld );
  4804. scope.expandByPoint( v1 );
  4805. }
  4806. }
  4807. }
  4808. }
  4809. } );
  4810. return this;
  4811. };
  4812. }(),
  4813. clone: function () {
  4814. return new this.constructor().copy( this );
  4815. },
  4816. copy: function ( box ) {
  4817. this.min.copy( box.min );
  4818. this.max.copy( box.max );
  4819. return this;
  4820. },
  4821. makeEmpty: function () {
  4822. this.min.x = this.min.y = this.min.z = + Infinity;
  4823. this.max.x = this.max.y = this.max.z = - Infinity;
  4824. return this;
  4825. },
  4826. isEmpty: function () {
  4827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4828. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4829. },
  4830. center: function ( optionalTarget ) {
  4831. var result = optionalTarget || new Vector3();
  4832. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4833. },
  4834. size: function ( optionalTarget ) {
  4835. var result = optionalTarget || new Vector3();
  4836. return result.subVectors( this.max, this.min );
  4837. },
  4838. expandByPoint: function ( point ) {
  4839. this.min.min( point );
  4840. this.max.max( point );
  4841. return this;
  4842. },
  4843. expandByVector: function ( vector ) {
  4844. this.min.sub( vector );
  4845. this.max.add( vector );
  4846. return this;
  4847. },
  4848. expandByScalar: function ( scalar ) {
  4849. this.min.addScalar( - scalar );
  4850. this.max.addScalar( scalar );
  4851. return this;
  4852. },
  4853. containsPoint: function ( point ) {
  4854. if ( point.x < this.min.x || point.x > this.max.x ||
  4855. point.y < this.min.y || point.y > this.max.y ||
  4856. point.z < this.min.z || point.z > this.max.z ) {
  4857. return false;
  4858. }
  4859. return true;
  4860. },
  4861. containsBox: function ( box ) {
  4862. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  4863. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  4864. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  4865. return true;
  4866. }
  4867. return false;
  4868. },
  4869. getParameter: function ( point, optionalTarget ) {
  4870. // This can potentially have a divide by zero if the box
  4871. // has a size dimension of 0.
  4872. var result = optionalTarget || new Vector3();
  4873. return result.set(
  4874. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4875. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4876. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4877. );
  4878. },
  4879. intersectsBox: function ( box ) {
  4880. // using 6 splitting planes to rule out intersections.
  4881. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  4882. box.max.y < this.min.y || box.min.y > this.max.y ||
  4883. box.max.z < this.min.z || box.min.z > this.max.z ) {
  4884. return false;
  4885. }
  4886. return true;
  4887. },
  4888. intersectsSphere: ( function () {
  4889. var closestPoint;
  4890. return function intersectsSphere( sphere ) {
  4891. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4892. // Find the point on the AABB closest to the sphere center.
  4893. this.clampPoint( sphere.center, closestPoint );
  4894. // If that point is inside the sphere, the AABB and sphere intersect.
  4895. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4896. };
  4897. } )(),
  4898. intersectsPlane: function ( plane ) {
  4899. // We compute the minimum and maximum dot product values. If those values
  4900. // are on the same side (back or front) of the plane, then there is no intersection.
  4901. var min, max;
  4902. if ( plane.normal.x > 0 ) {
  4903. min = plane.normal.x * this.min.x;
  4904. max = plane.normal.x * this.max.x;
  4905. } else {
  4906. min = plane.normal.x * this.max.x;
  4907. max = plane.normal.x * this.min.x;
  4908. }
  4909. if ( plane.normal.y > 0 ) {
  4910. min += plane.normal.y * this.min.y;
  4911. max += plane.normal.y * this.max.y;
  4912. } else {
  4913. min += plane.normal.y * this.max.y;
  4914. max += plane.normal.y * this.min.y;
  4915. }
  4916. if ( plane.normal.z > 0 ) {
  4917. min += plane.normal.z * this.min.z;
  4918. max += plane.normal.z * this.max.z;
  4919. } else {
  4920. min += plane.normal.z * this.max.z;
  4921. max += plane.normal.z * this.min.z;
  4922. }
  4923. return ( min <= plane.constant && max >= plane.constant );
  4924. },
  4925. clampPoint: function ( point, optionalTarget ) {
  4926. var result = optionalTarget || new Vector3();
  4927. return result.copy( point ).clamp( this.min, this.max );
  4928. },
  4929. distanceToPoint: function () {
  4930. var v1 = new Vector3();
  4931. return function distanceToPoint( point ) {
  4932. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4933. return clampedPoint.sub( point ).length();
  4934. };
  4935. }(),
  4936. getBoundingSphere: function () {
  4937. var v1 = new Vector3();
  4938. return function getBoundingSphere( optionalTarget ) {
  4939. var result = optionalTarget || new Sphere();
  4940. result.center = this.center();
  4941. result.radius = this.size( v1 ).length() * 0.5;
  4942. return result;
  4943. };
  4944. }(),
  4945. intersect: function ( box ) {
  4946. this.min.max( box.min );
  4947. this.max.min( box.max );
  4948. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  4949. if( this.isEmpty() ) this.makeEmpty();
  4950. return this;
  4951. },
  4952. union: function ( box ) {
  4953. this.min.min( box.min );
  4954. this.max.max( box.max );
  4955. return this;
  4956. },
  4957. applyMatrix4: function () {
  4958. var points = [
  4959. new Vector3(),
  4960. new Vector3(),
  4961. new Vector3(),
  4962. new Vector3(),
  4963. new Vector3(),
  4964. new Vector3(),
  4965. new Vector3(),
  4966. new Vector3()
  4967. ];
  4968. return function applyMatrix4( matrix ) {
  4969. // transform of empty box is an empty box.
  4970. if( this.isEmpty() ) return this;
  4971. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4972. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4973. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4974. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4975. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4976. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4977. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4978. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4979. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  4980. this.setFromPoints( points );
  4981. return this;
  4982. };
  4983. }(),
  4984. translate: function ( offset ) {
  4985. this.min.add( offset );
  4986. this.max.add( offset );
  4987. return this;
  4988. },
  4989. equals: function ( box ) {
  4990. return box.min.equals( this.min ) && box.max.equals( this.max );
  4991. }
  4992. };
  4993. /**
  4994. * @author bhouston / http://clara.io
  4995. * @author mrdoob / http://mrdoob.com/
  4996. */
  4997. function Sphere( center, radius ) {
  4998. this.center = ( center !== undefined ) ? center : new Vector3();
  4999. this.radius = ( radius !== undefined ) ? radius : 0;
  5000. }
  5001. Sphere.prototype = {
  5002. constructor: Sphere,
  5003. set: function ( center, radius ) {
  5004. this.center.copy( center );
  5005. this.radius = radius;
  5006. return this;
  5007. },
  5008. setFromPoints: function () {
  5009. var box = new Box3();
  5010. return function setFromPoints( points, optionalCenter ) {
  5011. var center = this.center;
  5012. if ( optionalCenter !== undefined ) {
  5013. center.copy( optionalCenter );
  5014. } else {
  5015. box.setFromPoints( points ).center( center );
  5016. }
  5017. var maxRadiusSq = 0;
  5018. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5019. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5020. }
  5021. this.radius = Math.sqrt( maxRadiusSq );
  5022. return this;
  5023. };
  5024. }(),
  5025. clone: function () {
  5026. return new this.constructor().copy( this );
  5027. },
  5028. copy: function ( sphere ) {
  5029. this.center.copy( sphere.center );
  5030. this.radius = sphere.radius;
  5031. return this;
  5032. },
  5033. empty: function () {
  5034. return ( this.radius <= 0 );
  5035. },
  5036. containsPoint: function ( point ) {
  5037. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5038. },
  5039. distanceToPoint: function ( point ) {
  5040. return ( point.distanceTo( this.center ) - this.radius );
  5041. },
  5042. intersectsSphere: function ( sphere ) {
  5043. var radiusSum = this.radius + sphere.radius;
  5044. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5045. },
  5046. intersectsBox: function ( box ) {
  5047. return box.intersectsSphere( this );
  5048. },
  5049. intersectsPlane: function ( plane ) {
  5050. // We use the following equation to compute the signed distance from
  5051. // the center of the sphere to the plane.
  5052. //
  5053. // distance = q * n - d
  5054. //
  5055. // If this distance is greater than the radius of the sphere,
  5056. // then there is no intersection.
  5057. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5058. },
  5059. clampPoint: function ( point, optionalTarget ) {
  5060. var deltaLengthSq = this.center.distanceToSquared( point );
  5061. var result = optionalTarget || new Vector3();
  5062. result.copy( point );
  5063. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5064. result.sub( this.center ).normalize();
  5065. result.multiplyScalar( this.radius ).add( this.center );
  5066. }
  5067. return result;
  5068. },
  5069. getBoundingBox: function ( optionalTarget ) {
  5070. var box = optionalTarget || new Box3();
  5071. box.set( this.center, this.center );
  5072. box.expandByScalar( this.radius );
  5073. return box;
  5074. },
  5075. applyMatrix4: function ( matrix ) {
  5076. this.center.applyMatrix4( matrix );
  5077. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5078. return this;
  5079. },
  5080. translate: function ( offset ) {
  5081. this.center.add( offset );
  5082. return this;
  5083. },
  5084. equals: function ( sphere ) {
  5085. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5086. }
  5087. };
  5088. /**
  5089. * @author alteredq / http://alteredqualia.com/
  5090. * @author WestLangley / http://github.com/WestLangley
  5091. * @author bhouston / http://clara.io
  5092. * @author tschw
  5093. */
  5094. function Matrix3() {
  5095. this.elements = new Float32Array( [
  5096. 1, 0, 0,
  5097. 0, 1, 0,
  5098. 0, 0, 1
  5099. ] );
  5100. if ( arguments.length > 0 ) {
  5101. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5102. }
  5103. }
  5104. Matrix3.prototype = {
  5105. constructor: Matrix3,
  5106. isMatrix3: true,
  5107. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5108. var te = this.elements;
  5109. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5110. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5111. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5112. return this;
  5113. },
  5114. identity: function () {
  5115. this.set(
  5116. 1, 0, 0,
  5117. 0, 1, 0,
  5118. 0, 0, 1
  5119. );
  5120. return this;
  5121. },
  5122. clone: function () {
  5123. return new this.constructor().fromArray( this.elements );
  5124. },
  5125. copy: function ( m ) {
  5126. var me = m.elements;
  5127. this.set(
  5128. me[ 0 ], me[ 3 ], me[ 6 ],
  5129. me[ 1 ], me[ 4 ], me[ 7 ],
  5130. me[ 2 ], me[ 5 ], me[ 8 ]
  5131. );
  5132. return this;
  5133. },
  5134. setFromMatrix4: function( m ) {
  5135. var me = m.elements;
  5136. this.set(
  5137. me[ 0 ], me[ 4 ], me[ 8 ],
  5138. me[ 1 ], me[ 5 ], me[ 9 ],
  5139. me[ 2 ], me[ 6 ], me[ 10 ]
  5140. );
  5141. return this;
  5142. },
  5143. applyToVector3Array: function () {
  5144. var v1;
  5145. return function applyToVector3Array( array, offset, length ) {
  5146. if ( v1 === undefined ) v1 = new Vector3();
  5147. if ( offset === undefined ) offset = 0;
  5148. if ( length === undefined ) length = array.length;
  5149. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  5150. v1.fromArray( array, j );
  5151. v1.applyMatrix3( this );
  5152. v1.toArray( array, j );
  5153. }
  5154. return array;
  5155. };
  5156. }(),
  5157. applyToBuffer: function () {
  5158. var v1;
  5159. return function applyToBuffer( buffer, offset, length ) {
  5160. if ( v1 === undefined ) v1 = new Vector3();
  5161. if ( offset === undefined ) offset = 0;
  5162. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  5163. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  5164. v1.x = buffer.getX( j );
  5165. v1.y = buffer.getY( j );
  5166. v1.z = buffer.getZ( j );
  5167. v1.applyMatrix3( this );
  5168. buffer.setXYZ( v1.x, v1.y, v1.z );
  5169. }
  5170. return buffer;
  5171. };
  5172. }(),
  5173. multiplyScalar: function ( s ) {
  5174. var te = this.elements;
  5175. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5176. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5177. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5178. return this;
  5179. },
  5180. determinant: function () {
  5181. var te = this.elements;
  5182. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5183. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5184. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5185. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5186. },
  5187. getInverse: function ( matrix, throwOnDegenerate ) {
  5188. if ( (matrix && matrix.isMatrix4) ) {
  5189. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5190. }
  5191. var me = matrix.elements,
  5192. te = this.elements,
  5193. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5194. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5195. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5196. t11 = n33 * n22 - n32 * n23,
  5197. t12 = n32 * n13 - n33 * n12,
  5198. t13 = n23 * n12 - n22 * n13,
  5199. det = n11 * t11 + n21 * t12 + n31 * t13;
  5200. if ( det === 0 ) {
  5201. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5202. if ( throwOnDegenerate === true ) {
  5203. throw new Error( msg );
  5204. } else {
  5205. console.warn( msg );
  5206. }
  5207. return this.identity();
  5208. }
  5209. var detInv = 1 / det;
  5210. te[ 0 ] = t11 * detInv;
  5211. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5212. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5213. te[ 3 ] = t12 * detInv;
  5214. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5215. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5216. te[ 6 ] = t13 * detInv;
  5217. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5218. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5219. return this;
  5220. },
  5221. transpose: function () {
  5222. var tmp, m = this.elements;
  5223. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5224. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5225. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5226. return this;
  5227. },
  5228. flattenToArrayOffset: function ( array, offset ) {
  5229. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  5230. "- just use .toArray instead." );
  5231. return this.toArray( array, offset );
  5232. },
  5233. getNormalMatrix: function ( matrix4 ) {
  5234. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5235. },
  5236. transposeIntoArray: function ( r ) {
  5237. var m = this.elements;
  5238. r[ 0 ] = m[ 0 ];
  5239. r[ 1 ] = m[ 3 ];
  5240. r[ 2 ] = m[ 6 ];
  5241. r[ 3 ] = m[ 1 ];
  5242. r[ 4 ] = m[ 4 ];
  5243. r[ 5 ] = m[ 7 ];
  5244. r[ 6 ] = m[ 2 ];
  5245. r[ 7 ] = m[ 5 ];
  5246. r[ 8 ] = m[ 8 ];
  5247. return this;
  5248. },
  5249. fromArray: function ( array ) {
  5250. this.elements.set( array );
  5251. return this;
  5252. },
  5253. toArray: function ( array, offset ) {
  5254. if ( array === undefined ) array = [];
  5255. if ( offset === undefined ) offset = 0;
  5256. var te = this.elements;
  5257. array[ offset ] = te[ 0 ];
  5258. array[ offset + 1 ] = te[ 1 ];
  5259. array[ offset + 2 ] = te[ 2 ];
  5260. array[ offset + 3 ] = te[ 3 ];
  5261. array[ offset + 4 ] = te[ 4 ];
  5262. array[ offset + 5 ] = te[ 5 ];
  5263. array[ offset + 6 ] = te[ 6 ];
  5264. array[ offset + 7 ] = te[ 7 ];
  5265. array[ offset + 8 ] = te[ 8 ];
  5266. return array;
  5267. }
  5268. };
  5269. /**
  5270. * @author bhouston / http://clara.io
  5271. */
  5272. function Plane( normal, constant ) {
  5273. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5274. this.constant = ( constant !== undefined ) ? constant : 0;
  5275. }
  5276. Plane.prototype = {
  5277. constructor: Plane,
  5278. set: function ( normal, constant ) {
  5279. this.normal.copy( normal );
  5280. this.constant = constant;
  5281. return this;
  5282. },
  5283. setComponents: function ( x, y, z, w ) {
  5284. this.normal.set( x, y, z );
  5285. this.constant = w;
  5286. return this;
  5287. },
  5288. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5289. this.normal.copy( normal );
  5290. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5291. return this;
  5292. },
  5293. setFromCoplanarPoints: function () {
  5294. var v1 = new Vector3();
  5295. var v2 = new Vector3();
  5296. return function setFromCoplanarPoints( a, b, c ) {
  5297. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5298. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5299. this.setFromNormalAndCoplanarPoint( normal, a );
  5300. return this;
  5301. };
  5302. }(),
  5303. clone: function () {
  5304. return new this.constructor().copy( this );
  5305. },
  5306. copy: function ( plane ) {
  5307. this.normal.copy( plane.normal );
  5308. this.constant = plane.constant;
  5309. return this;
  5310. },
  5311. normalize: function () {
  5312. // Note: will lead to a divide by zero if the plane is invalid.
  5313. var inverseNormalLength = 1.0 / this.normal.length();
  5314. this.normal.multiplyScalar( inverseNormalLength );
  5315. this.constant *= inverseNormalLength;
  5316. return this;
  5317. },
  5318. negate: function () {
  5319. this.constant *= - 1;
  5320. this.normal.negate();
  5321. return this;
  5322. },
  5323. distanceToPoint: function ( point ) {
  5324. return this.normal.dot( point ) + this.constant;
  5325. },
  5326. distanceToSphere: function ( sphere ) {
  5327. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5328. },
  5329. projectPoint: function ( point, optionalTarget ) {
  5330. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5331. },
  5332. orthoPoint: function ( point, optionalTarget ) {
  5333. var perpendicularMagnitude = this.distanceToPoint( point );
  5334. var result = optionalTarget || new Vector3();
  5335. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5336. },
  5337. intersectLine: function () {
  5338. var v1 = new Vector3();
  5339. return function intersectLine( line, optionalTarget ) {
  5340. var result = optionalTarget || new Vector3();
  5341. var direction = line.delta( v1 );
  5342. var denominator = this.normal.dot( direction );
  5343. if ( denominator === 0 ) {
  5344. // line is coplanar, return origin
  5345. if ( this.distanceToPoint( line.start ) === 0 ) {
  5346. return result.copy( line.start );
  5347. }
  5348. // Unsure if this is the correct method to handle this case.
  5349. return undefined;
  5350. }
  5351. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5352. if ( t < 0 || t > 1 ) {
  5353. return undefined;
  5354. }
  5355. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5356. };
  5357. }(),
  5358. intersectsLine: function ( line ) {
  5359. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5360. var startSign = this.distanceToPoint( line.start );
  5361. var endSign = this.distanceToPoint( line.end );
  5362. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5363. },
  5364. intersectsBox: function ( box ) {
  5365. return box.intersectsPlane( this );
  5366. },
  5367. intersectsSphere: function ( sphere ) {
  5368. return sphere.intersectsPlane( this );
  5369. },
  5370. coplanarPoint: function ( optionalTarget ) {
  5371. var result = optionalTarget || new Vector3();
  5372. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5373. },
  5374. applyMatrix4: function () {
  5375. var v1 = new Vector3();
  5376. var m1 = new Matrix3();
  5377. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5378. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5379. // transform normal based on theory here:
  5380. // http://www.songho.ca/opengl/gl_normaltransform.html
  5381. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5382. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5383. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5384. this.constant = - referencePoint.dot( normal );
  5385. return this;
  5386. };
  5387. }(),
  5388. translate: function ( offset ) {
  5389. this.constant = this.constant - offset.dot( this.normal );
  5390. return this;
  5391. },
  5392. equals: function ( plane ) {
  5393. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5394. }
  5395. };
  5396. /**
  5397. * @author mrdoob / http://mrdoob.com/
  5398. * @author alteredq / http://alteredqualia.com/
  5399. * @author bhouston / http://clara.io
  5400. */
  5401. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5402. this.planes = [
  5403. ( p0 !== undefined ) ? p0 : new Plane(),
  5404. ( p1 !== undefined ) ? p1 : new Plane(),
  5405. ( p2 !== undefined ) ? p2 : new Plane(),
  5406. ( p3 !== undefined ) ? p3 : new Plane(),
  5407. ( p4 !== undefined ) ? p4 : new Plane(),
  5408. ( p5 !== undefined ) ? p5 : new Plane()
  5409. ];
  5410. }
  5411. Frustum.prototype = {
  5412. constructor: Frustum,
  5413. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5414. var planes = this.planes;
  5415. planes[ 0 ].copy( p0 );
  5416. planes[ 1 ].copy( p1 );
  5417. planes[ 2 ].copy( p2 );
  5418. planes[ 3 ].copy( p3 );
  5419. planes[ 4 ].copy( p4 );
  5420. planes[ 5 ].copy( p5 );
  5421. return this;
  5422. },
  5423. clone: function () {
  5424. return new this.constructor().copy( this );
  5425. },
  5426. copy: function ( frustum ) {
  5427. var planes = this.planes;
  5428. for ( var i = 0; i < 6; i ++ ) {
  5429. planes[ i ].copy( frustum.planes[ i ] );
  5430. }
  5431. return this;
  5432. },
  5433. setFromMatrix: function ( m ) {
  5434. var planes = this.planes;
  5435. var me = m.elements;
  5436. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5437. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5438. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5439. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5440. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5441. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5442. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5443. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5444. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5445. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5446. return this;
  5447. },
  5448. intersectsObject: function () {
  5449. var sphere = new Sphere();
  5450. return function intersectsObject( object ) {
  5451. var geometry = object.geometry;
  5452. if ( geometry.boundingSphere === null )
  5453. geometry.computeBoundingSphere();
  5454. sphere.copy( geometry.boundingSphere )
  5455. .applyMatrix4( object.matrixWorld );
  5456. return this.intersectsSphere( sphere );
  5457. };
  5458. }(),
  5459. intersectsSprite: function () {
  5460. var sphere = new Sphere();
  5461. return function intersectsSprite( sprite ) {
  5462. sphere.center.set( 0, 0, 0 );
  5463. sphere.radius = 0.7071067811865476;
  5464. sphere.applyMatrix4( sprite.matrixWorld );
  5465. return this.intersectsSphere( sphere );
  5466. };
  5467. }(),
  5468. intersectsSphere: function ( sphere ) {
  5469. var planes = this.planes;
  5470. var center = sphere.center;
  5471. var negRadius = - sphere.radius;
  5472. for ( var i = 0; i < 6; i ++ ) {
  5473. var distance = planes[ i ].distanceToPoint( center );
  5474. if ( distance < negRadius ) {
  5475. return false;
  5476. }
  5477. }
  5478. return true;
  5479. },
  5480. intersectsBox: function () {
  5481. var p1 = new Vector3(),
  5482. p2 = new Vector3();
  5483. return function intersectsBox( box ) {
  5484. var planes = this.planes;
  5485. for ( var i = 0; i < 6 ; i ++ ) {
  5486. var plane = planes[ i ];
  5487. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5488. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5489. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5490. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5491. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5492. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5493. var d1 = plane.distanceToPoint( p1 );
  5494. var d2 = plane.distanceToPoint( p2 );
  5495. // if both outside plane, no intersection
  5496. if ( d1 < 0 && d2 < 0 ) {
  5497. return false;
  5498. }
  5499. }
  5500. return true;
  5501. };
  5502. }(),
  5503. containsPoint: function ( point ) {
  5504. var planes = this.planes;
  5505. for ( var i = 0; i < 6; i ++ ) {
  5506. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5507. return false;
  5508. }
  5509. }
  5510. return true;
  5511. }
  5512. };
  5513. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5514. var _gl = _renderer.context,
  5515. _state = _renderer.state,
  5516. _frustum = new Frustum(),
  5517. _projScreenMatrix = new Matrix4(),
  5518. _lightShadows = _lights.shadows,
  5519. _shadowMapSize = new Vector2(),
  5520. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5521. _lookTarget = new Vector3(),
  5522. _lightPositionWorld = new Vector3(),
  5523. _renderList = [],
  5524. _MorphingFlag = 1,
  5525. _SkinningFlag = 2,
  5526. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5527. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5528. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5529. _materialCache = {};
  5530. var cubeDirections = [
  5531. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5532. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5533. ];
  5534. var cubeUps = [
  5535. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5536. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5537. ];
  5538. var cube2DViewPorts = [
  5539. new Vector4(), new Vector4(), new Vector4(),
  5540. new Vector4(), new Vector4(), new Vector4()
  5541. ];
  5542. // init
  5543. var depthMaterialTemplate = new MeshDepthMaterial();
  5544. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5545. depthMaterialTemplate.clipping = true;
  5546. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5547. var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms );
  5548. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5549. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5550. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5551. var depthMaterial = depthMaterialTemplate.clone();
  5552. depthMaterial.morphTargets = useMorphing;
  5553. depthMaterial.skinning = useSkinning;
  5554. _depthMaterials[ i ] = depthMaterial;
  5555. var distanceMaterial = new ShaderMaterial( {
  5556. defines: {
  5557. 'USE_SHADOWMAP': ''
  5558. },
  5559. uniforms: distanceUniforms,
  5560. vertexShader: distanceShader.vertexShader,
  5561. fragmentShader: distanceShader.fragmentShader,
  5562. morphTargets: useMorphing,
  5563. skinning: useSkinning,
  5564. clipping: true
  5565. } );
  5566. _distanceMaterials[ i ] = distanceMaterial;
  5567. }
  5568. //
  5569. var scope = this;
  5570. this.enabled = false;
  5571. this.autoUpdate = true;
  5572. this.needsUpdate = false;
  5573. this.type = PCFShadowMap;
  5574. this.renderReverseSided = true;
  5575. this.renderSingleSided = true;
  5576. this.render = function ( scene, camera ) {
  5577. if ( scope.enabled === false ) return;
  5578. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5579. if ( _lightShadows.length === 0 ) return;
  5580. // Set GL state for depth map.
  5581. _state.clearColor( 1, 1, 1, 1 );
  5582. _state.disable( _gl.BLEND );
  5583. _state.setDepthTest( true );
  5584. _state.setScissorTest( false );
  5585. // render depth map
  5586. var faceCount, isPointLight;
  5587. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5588. var light = _lightShadows[ i ];
  5589. var shadow = light.shadow;
  5590. if ( shadow === undefined ) {
  5591. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5592. continue;
  5593. }
  5594. var shadowCamera = shadow.camera;
  5595. _shadowMapSize.copy( shadow.mapSize );
  5596. _shadowMapSize.min( _maxShadowMapSize );
  5597. if ( (light && light.isPointLight) ) {
  5598. faceCount = 6;
  5599. isPointLight = true;
  5600. var vpWidth = _shadowMapSize.x;
  5601. var vpHeight = _shadowMapSize.y;
  5602. // These viewports map a cube-map onto a 2D texture with the
  5603. // following orientation:
  5604. //
  5605. // xzXZ
  5606. // y Y
  5607. //
  5608. // X - Positive x direction
  5609. // x - Negative x direction
  5610. // Y - Positive y direction
  5611. // y - Negative y direction
  5612. // Z - Positive z direction
  5613. // z - Negative z direction
  5614. // positive X
  5615. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5616. // negative X
  5617. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5618. // positive Z
  5619. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5620. // negative Z
  5621. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5622. // positive Y
  5623. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5624. // negative Y
  5625. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5626. _shadowMapSize.x *= 4.0;
  5627. _shadowMapSize.y *= 2.0;
  5628. } else {
  5629. faceCount = 1;
  5630. isPointLight = false;
  5631. }
  5632. if ( shadow.map === null ) {
  5633. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5634. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5635. shadowCamera.updateProjectionMatrix();
  5636. }
  5637. if ( (shadow && shadow.isSpotLightShadow) ) {
  5638. shadow.update( light );
  5639. }
  5640. var shadowMap = shadow.map;
  5641. var shadowMatrix = shadow.matrix;
  5642. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5643. shadowCamera.position.copy( _lightPositionWorld );
  5644. _renderer.setRenderTarget( shadowMap );
  5645. _renderer.clear();
  5646. // render shadow map for each cube face (if omni-directional) or
  5647. // run a single pass if not
  5648. for ( var face = 0; face < faceCount; face ++ ) {
  5649. if ( isPointLight ) {
  5650. _lookTarget.copy( shadowCamera.position );
  5651. _lookTarget.add( cubeDirections[ face ] );
  5652. shadowCamera.up.copy( cubeUps[ face ] );
  5653. shadowCamera.lookAt( _lookTarget );
  5654. var vpDimensions = cube2DViewPorts[ face ];
  5655. _state.viewport( vpDimensions );
  5656. } else {
  5657. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5658. shadowCamera.lookAt( _lookTarget );
  5659. }
  5660. shadowCamera.updateMatrixWorld();
  5661. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5662. // compute shadow matrix
  5663. shadowMatrix.set(
  5664. 0.5, 0.0, 0.0, 0.5,
  5665. 0.0, 0.5, 0.0, 0.5,
  5666. 0.0, 0.0, 0.5, 0.5,
  5667. 0.0, 0.0, 0.0, 1.0
  5668. );
  5669. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5670. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5671. // update camera matrices and frustum
  5672. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5673. _frustum.setFromMatrix( _projScreenMatrix );
  5674. // set object matrices & frustum culling
  5675. _renderList.length = 0;
  5676. projectObject( scene, camera, shadowCamera );
  5677. // render shadow map
  5678. // render regular objects
  5679. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5680. var object = _renderList[ j ];
  5681. var geometry = _objects.update( object );
  5682. var material = object.material;
  5683. if ( (material && material.isMultiMaterial) ) {
  5684. var groups = geometry.groups;
  5685. var materials = material.materials;
  5686. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5687. var group = groups[ k ];
  5688. var groupMaterial = materials[ group.materialIndex ];
  5689. if ( groupMaterial.visible === true ) {
  5690. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5691. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5692. }
  5693. }
  5694. } else {
  5695. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5696. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5697. }
  5698. }
  5699. }
  5700. }
  5701. // Restore GL state.
  5702. var clearColor = _renderer.getClearColor(),
  5703. clearAlpha = _renderer.getClearAlpha();
  5704. _renderer.setClearColor( clearColor, clearAlpha );
  5705. scope.needsUpdate = false;
  5706. };
  5707. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5708. var geometry = object.geometry;
  5709. var result = null;
  5710. var materialVariants = _depthMaterials;
  5711. var customMaterial = object.customDepthMaterial;
  5712. if ( isPointLight ) {
  5713. materialVariants = _distanceMaterials;
  5714. customMaterial = object.customDistanceMaterial;
  5715. }
  5716. if ( ! customMaterial ) {
  5717. var useMorphing = false;
  5718. if ( material.morphTargets ) {
  5719. if ( (geometry && geometry.isBufferGeometry) ) {
  5720. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5721. } else if ( (geometry && geometry.isGeometry) ) {
  5722. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5723. }
  5724. }
  5725. var useSkinning = object.isSkinnedMesh && material.skinning;
  5726. var variantIndex = 0;
  5727. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5728. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5729. result = materialVariants[ variantIndex ];
  5730. } else {
  5731. result = customMaterial;
  5732. }
  5733. if ( _renderer.localClippingEnabled &&
  5734. material.clipShadows === true &&
  5735. material.clippingPlanes.length !== 0 ) {
  5736. // in this case we need a unique material instance reflecting the
  5737. // appropriate state
  5738. var keyA = result.uuid, keyB = material.uuid;
  5739. var materialsForVariant = _materialCache[ keyA ];
  5740. if ( materialsForVariant === undefined ) {
  5741. materialsForVariant = {};
  5742. _materialCache[ keyA ] = materialsForVariant;
  5743. }
  5744. var cachedMaterial = materialsForVariant[ keyB ];
  5745. if ( cachedMaterial === undefined ) {
  5746. cachedMaterial = result.clone();
  5747. materialsForVariant[ keyB ] = cachedMaterial;
  5748. }
  5749. result = cachedMaterial;
  5750. }
  5751. result.visible = material.visible;
  5752. result.wireframe = material.wireframe;
  5753. var side = material.side;
  5754. if ( scope.renderSingleSided && side == DoubleSide ) {
  5755. side = FrontSide;
  5756. }
  5757. if ( scope.renderReverseSided ) {
  5758. if ( side === FrontSide ) side = BackSide;
  5759. else if ( side === BackSide ) side = FrontSide;
  5760. }
  5761. result.side = side;
  5762. result.clipShadows = material.clipShadows;
  5763. result.clippingPlanes = material.clippingPlanes;
  5764. result.wireframeLinewidth = material.wireframeLinewidth;
  5765. result.linewidth = material.linewidth;
  5766. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5767. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5768. }
  5769. return result;
  5770. }
  5771. function projectObject( object, camera, shadowCamera ) {
  5772. if ( object.visible === false ) return;
  5773. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5774. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5775. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5776. var material = object.material;
  5777. if ( material.visible === true ) {
  5778. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5779. _renderList.push( object );
  5780. }
  5781. }
  5782. }
  5783. var children = object.children;
  5784. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5785. projectObject( children[ i ], camera, shadowCamera );
  5786. }
  5787. }
  5788. }
  5789. /**
  5790. * @author mrdoob / http://mrdoob.com/
  5791. */
  5792. function BufferAttribute( array, itemSize, normalized ) {
  5793. if ( Array.isArray( array ) ) {
  5794. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5795. }
  5796. this.uuid = exports.Math.generateUUID();
  5797. this.array = array;
  5798. this.itemSize = itemSize;
  5799. this.normalized = normalized === true;
  5800. this.dynamic = false;
  5801. this.updateRange = { offset: 0, count: - 1 };
  5802. this.version = 0;
  5803. }
  5804. BufferAttribute.prototype = {
  5805. constructor: BufferAttribute,
  5806. isBufferAttribute: true,
  5807. get count() {
  5808. return this.array.length / this.itemSize;
  5809. },
  5810. set needsUpdate( value ) {
  5811. if ( value === true ) this.version ++;
  5812. },
  5813. setDynamic: function ( value ) {
  5814. this.dynamic = value;
  5815. return this;
  5816. },
  5817. copy: function ( source ) {
  5818. this.array = new source.array.constructor( source.array );
  5819. this.itemSize = source.itemSize;
  5820. this.normalized = source.normalized;
  5821. this.dynamic = source.dynamic;
  5822. return this;
  5823. },
  5824. copyAt: function ( index1, attribute, index2 ) {
  5825. index1 *= this.itemSize;
  5826. index2 *= attribute.itemSize;
  5827. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5828. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5829. }
  5830. return this;
  5831. },
  5832. copyArray: function ( array ) {
  5833. this.array.set( array );
  5834. return this;
  5835. },
  5836. copyColorsArray: function ( colors ) {
  5837. var array = this.array, offset = 0;
  5838. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5839. var color = colors[ i ];
  5840. if ( color === undefined ) {
  5841. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5842. color = new Color();
  5843. }
  5844. array[ offset ++ ] = color.r;
  5845. array[ offset ++ ] = color.g;
  5846. array[ offset ++ ] = color.b;
  5847. }
  5848. return this;
  5849. },
  5850. copyIndicesArray: function ( indices ) {
  5851. var array = this.array, offset = 0;
  5852. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5853. var index = indices[ i ];
  5854. array[ offset ++ ] = index.a;
  5855. array[ offset ++ ] = index.b;
  5856. array[ offset ++ ] = index.c;
  5857. }
  5858. return this;
  5859. },
  5860. copyVector2sArray: function ( vectors ) {
  5861. var array = this.array, offset = 0;
  5862. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5863. var vector = vectors[ i ];
  5864. if ( vector === undefined ) {
  5865. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5866. vector = new Vector2();
  5867. }
  5868. array[ offset ++ ] = vector.x;
  5869. array[ offset ++ ] = vector.y;
  5870. }
  5871. return this;
  5872. },
  5873. copyVector3sArray: function ( vectors ) {
  5874. var array = this.array, offset = 0;
  5875. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5876. var vector = vectors[ i ];
  5877. if ( vector === undefined ) {
  5878. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5879. vector = new Vector3();
  5880. }
  5881. array[ offset ++ ] = vector.x;
  5882. array[ offset ++ ] = vector.y;
  5883. array[ offset ++ ] = vector.z;
  5884. }
  5885. return this;
  5886. },
  5887. copyVector4sArray: function ( vectors ) {
  5888. var array = this.array, offset = 0;
  5889. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5890. var vector = vectors[ i ];
  5891. if ( vector === undefined ) {
  5892. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5893. vector = new Vector4();
  5894. }
  5895. array[ offset ++ ] = vector.x;
  5896. array[ offset ++ ] = vector.y;
  5897. array[ offset ++ ] = vector.z;
  5898. array[ offset ++ ] = vector.w;
  5899. }
  5900. return this;
  5901. },
  5902. set: function ( value, offset ) {
  5903. if ( offset === undefined ) offset = 0;
  5904. this.array.set( value, offset );
  5905. return this;
  5906. },
  5907. getX: function ( index ) {
  5908. return this.array[ index * this.itemSize ];
  5909. },
  5910. setX: function ( index, x ) {
  5911. this.array[ index * this.itemSize ] = x;
  5912. return this;
  5913. },
  5914. getY: function ( index ) {
  5915. return this.array[ index * this.itemSize + 1 ];
  5916. },
  5917. setY: function ( index, y ) {
  5918. this.array[ index * this.itemSize + 1 ] = y;
  5919. return this;
  5920. },
  5921. getZ: function ( index ) {
  5922. return this.array[ index * this.itemSize + 2 ];
  5923. },
  5924. setZ: function ( index, z ) {
  5925. this.array[ index * this.itemSize + 2 ] = z;
  5926. return this;
  5927. },
  5928. getW: function ( index ) {
  5929. return this.array[ index * this.itemSize + 3 ];
  5930. },
  5931. setW: function ( index, w ) {
  5932. this.array[ index * this.itemSize + 3 ] = w;
  5933. return this;
  5934. },
  5935. setXY: function ( index, x, y ) {
  5936. index *= this.itemSize;
  5937. this.array[ index + 0 ] = x;
  5938. this.array[ index + 1 ] = y;
  5939. return this;
  5940. },
  5941. setXYZ: function ( index, x, y, z ) {
  5942. index *= this.itemSize;
  5943. this.array[ index + 0 ] = x;
  5944. this.array[ index + 1 ] = y;
  5945. this.array[ index + 2 ] = z;
  5946. return this;
  5947. },
  5948. setXYZW: function ( index, x, y, z, w ) {
  5949. index *= this.itemSize;
  5950. this.array[ index + 0 ] = x;
  5951. this.array[ index + 1 ] = y;
  5952. this.array[ index + 2 ] = z;
  5953. this.array[ index + 3 ] = w;
  5954. return this;
  5955. },
  5956. clone: function () {
  5957. return new this.constructor().copy( this );
  5958. }
  5959. };
  5960. //
  5961. function Int8Attribute( array, itemSize ) {
  5962. return new BufferAttribute( new Int8Array( array ), itemSize );
  5963. }
  5964. function Uint8Attribute( array, itemSize ) {
  5965. return new BufferAttribute( new Uint8Array( array ), itemSize );
  5966. }
  5967. function Uint8ClampedAttribute( array, itemSize ) {
  5968. return new BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5969. }
  5970. function Int16Attribute( array, itemSize ) {
  5971. return new BufferAttribute( new Int16Array( array ), itemSize );
  5972. }
  5973. function Uint16Attribute( array, itemSize ) {
  5974. return new BufferAttribute( new Uint16Array( array ), itemSize );
  5975. }
  5976. function Int32Attribute( array, itemSize ) {
  5977. return new BufferAttribute( new Int32Array( array ), itemSize );
  5978. }
  5979. function Uint32Attribute( array, itemSize ) {
  5980. return new BufferAttribute( new Uint32Array( array ), itemSize );
  5981. }
  5982. function Float32Attribute( array, itemSize ) {
  5983. return new BufferAttribute( new Float32Array( array ), itemSize );
  5984. }
  5985. function Float64Attribute( array, itemSize ) {
  5986. return new BufferAttribute( new Float64Array( array ), itemSize );
  5987. }
  5988. // Deprecated
  5989. function DynamicBufferAttribute( array, itemSize ) {
  5990. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5991. return new BufferAttribute( array, itemSize ).setDynamic( true );
  5992. }
  5993. /**
  5994. * @author mrdoob / http://mrdoob.com/
  5995. * @author alteredq / http://alteredqualia.com/
  5996. */
  5997. function Face3( a, b, c, normal, color, materialIndex ) {
  5998. this.a = a;
  5999. this.b = b;
  6000. this.c = c;
  6001. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  6002. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6003. this.color = (color && color.isColor) ? color : new Color();
  6004. this.vertexColors = Array.isArray( color ) ? color : [];
  6005. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6006. }
  6007. Face3.prototype = {
  6008. constructor: Face3,
  6009. clone: function () {
  6010. return new this.constructor().copy( this );
  6011. },
  6012. copy: function ( source ) {
  6013. this.a = source.a;
  6014. this.b = source.b;
  6015. this.c = source.c;
  6016. this.normal.copy( source.normal );
  6017. this.color.copy( source.color );
  6018. this.materialIndex = source.materialIndex;
  6019. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6020. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6021. }
  6022. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6023. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6024. }
  6025. return this;
  6026. }
  6027. };
  6028. /**
  6029. * @author mrdoob / http://mrdoob.com/
  6030. * @author WestLangley / http://github.com/WestLangley
  6031. * @author bhouston / http://clara.io
  6032. */
  6033. function Euler( x, y, z, order ) {
  6034. this._x = x || 0;
  6035. this._y = y || 0;
  6036. this._z = z || 0;
  6037. this._order = order || Euler.DefaultOrder;
  6038. }
  6039. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6040. Euler.DefaultOrder = 'XYZ';
  6041. Euler.prototype = {
  6042. constructor: Euler,
  6043. isEuler: true,
  6044. get x () {
  6045. return this._x;
  6046. },
  6047. set x ( value ) {
  6048. this._x = value;
  6049. this.onChangeCallback();
  6050. },
  6051. get y () {
  6052. return this._y;
  6053. },
  6054. set y ( value ) {
  6055. this._y = value;
  6056. this.onChangeCallback();
  6057. },
  6058. get z () {
  6059. return this._z;
  6060. },
  6061. set z ( value ) {
  6062. this._z = value;
  6063. this.onChangeCallback();
  6064. },
  6065. get order () {
  6066. return this._order;
  6067. },
  6068. set order ( value ) {
  6069. this._order = value;
  6070. this.onChangeCallback();
  6071. },
  6072. set: function ( x, y, z, order ) {
  6073. this._x = x;
  6074. this._y = y;
  6075. this._z = z;
  6076. this._order = order || this._order;
  6077. this.onChangeCallback();
  6078. return this;
  6079. },
  6080. clone: function () {
  6081. return new this.constructor( this._x, this._y, this._z, this._order );
  6082. },
  6083. copy: function ( euler ) {
  6084. this._x = euler._x;
  6085. this._y = euler._y;
  6086. this._z = euler._z;
  6087. this._order = euler._order;
  6088. this.onChangeCallback();
  6089. return this;
  6090. },
  6091. setFromRotationMatrix: function ( m, order, update ) {
  6092. var clamp = exports.Math.clamp;
  6093. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6094. var te = m.elements;
  6095. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6096. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6097. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6098. order = order || this._order;
  6099. if ( order === 'XYZ' ) {
  6100. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6101. if ( Math.abs( m13 ) < 0.99999 ) {
  6102. this._x = Math.atan2( - m23, m33 );
  6103. this._z = Math.atan2( - m12, m11 );
  6104. } else {
  6105. this._x = Math.atan2( m32, m22 );
  6106. this._z = 0;
  6107. }
  6108. } else if ( order === 'YXZ' ) {
  6109. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6110. if ( Math.abs( m23 ) < 0.99999 ) {
  6111. this._y = Math.atan2( m13, m33 );
  6112. this._z = Math.atan2( m21, m22 );
  6113. } else {
  6114. this._y = Math.atan2( - m31, m11 );
  6115. this._z = 0;
  6116. }
  6117. } else if ( order === 'ZXY' ) {
  6118. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6119. if ( Math.abs( m32 ) < 0.99999 ) {
  6120. this._y = Math.atan2( - m31, m33 );
  6121. this._z = Math.atan2( - m12, m22 );
  6122. } else {
  6123. this._y = 0;
  6124. this._z = Math.atan2( m21, m11 );
  6125. }
  6126. } else if ( order === 'ZYX' ) {
  6127. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6128. if ( Math.abs( m31 ) < 0.99999 ) {
  6129. this._x = Math.atan2( m32, m33 );
  6130. this._z = Math.atan2( m21, m11 );
  6131. } else {
  6132. this._x = 0;
  6133. this._z = Math.atan2( - m12, m22 );
  6134. }
  6135. } else if ( order === 'YZX' ) {
  6136. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6137. if ( Math.abs( m21 ) < 0.99999 ) {
  6138. this._x = Math.atan2( - m23, m22 );
  6139. this._y = Math.atan2( - m31, m11 );
  6140. } else {
  6141. this._x = 0;
  6142. this._y = Math.atan2( m13, m33 );
  6143. }
  6144. } else if ( order === 'XZY' ) {
  6145. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6146. if ( Math.abs( m12 ) < 0.99999 ) {
  6147. this._x = Math.atan2( m32, m22 );
  6148. this._y = Math.atan2( m13, m11 );
  6149. } else {
  6150. this._x = Math.atan2( - m23, m33 );
  6151. this._y = 0;
  6152. }
  6153. } else {
  6154. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6155. }
  6156. this._order = order;
  6157. if ( update !== false ) this.onChangeCallback();
  6158. return this;
  6159. },
  6160. setFromQuaternion: function () {
  6161. var matrix;
  6162. return function setFromQuaternion( q, order, update ) {
  6163. if ( matrix === undefined ) matrix = new Matrix4();
  6164. matrix.makeRotationFromQuaternion( q );
  6165. return this.setFromRotationMatrix( matrix, order, update );
  6166. };
  6167. }(),
  6168. setFromVector3: function ( v, order ) {
  6169. return this.set( v.x, v.y, v.z, order || this._order );
  6170. },
  6171. reorder: function () {
  6172. // WARNING: this discards revolution information -bhouston
  6173. var q = new Quaternion();
  6174. return function reorder( newOrder ) {
  6175. q.setFromEuler( this );
  6176. return this.setFromQuaternion( q, newOrder );
  6177. };
  6178. }(),
  6179. equals: function ( euler ) {
  6180. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6181. },
  6182. fromArray: function ( array ) {
  6183. this._x = array[ 0 ];
  6184. this._y = array[ 1 ];
  6185. this._z = array[ 2 ];
  6186. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6187. this.onChangeCallback();
  6188. return this;
  6189. },
  6190. toArray: function ( array, offset ) {
  6191. if ( array === undefined ) array = [];
  6192. if ( offset === undefined ) offset = 0;
  6193. array[ offset ] = this._x;
  6194. array[ offset + 1 ] = this._y;
  6195. array[ offset + 2 ] = this._z;
  6196. array[ offset + 3 ] = this._order;
  6197. return array;
  6198. },
  6199. toVector3: function ( optionalResult ) {
  6200. if ( optionalResult ) {
  6201. return optionalResult.set( this._x, this._y, this._z );
  6202. } else {
  6203. return new Vector3( this._x, this._y, this._z );
  6204. }
  6205. },
  6206. onChange: function ( callback ) {
  6207. this.onChangeCallback = callback;
  6208. return this;
  6209. },
  6210. onChangeCallback: function () {}
  6211. };
  6212. /**
  6213. * @author mrdoob / http://mrdoob.com/
  6214. */
  6215. function Layers() {
  6216. this.mask = 1;
  6217. }
  6218. Layers.prototype = {
  6219. constructor: Layers,
  6220. set: function ( channel ) {
  6221. this.mask = 1 << channel;
  6222. },
  6223. enable: function ( channel ) {
  6224. this.mask |= 1 << channel;
  6225. },
  6226. toggle: function ( channel ) {
  6227. this.mask ^= 1 << channel;
  6228. },
  6229. disable: function ( channel ) {
  6230. this.mask &= ~ ( 1 << channel );
  6231. },
  6232. test: function ( layers ) {
  6233. return ( this.mask & layers.mask ) !== 0;
  6234. }
  6235. };
  6236. /**
  6237. * @author mrdoob / http://mrdoob.com/
  6238. * @author mikael emtinger / http://gomo.se/
  6239. * @author alteredq / http://alteredqualia.com/
  6240. * @author WestLangley / http://github.com/WestLangley
  6241. * @author elephantatwork / www.elephantatwork.ch
  6242. */
  6243. function Object3D() {
  6244. Object.defineProperty( this, 'id', { value: Object3DIdCount() } );
  6245. this.uuid = exports.Math.generateUUID();
  6246. this.name = '';
  6247. this.type = 'Object3D';
  6248. this.parent = null;
  6249. this.children = [];
  6250. this.up = Object3D.DefaultUp.clone();
  6251. var position = new Vector3();
  6252. var rotation = new Euler();
  6253. var quaternion = new Quaternion();
  6254. var scale = new Vector3( 1, 1, 1 );
  6255. function onRotationChange() {
  6256. quaternion.setFromEuler( rotation, false );
  6257. }
  6258. function onQuaternionChange() {
  6259. rotation.setFromQuaternion( quaternion, undefined, false );
  6260. }
  6261. rotation.onChange( onRotationChange );
  6262. quaternion.onChange( onQuaternionChange );
  6263. Object.defineProperties( this, {
  6264. position: {
  6265. enumerable: true,
  6266. value: position
  6267. },
  6268. rotation: {
  6269. enumerable: true,
  6270. value: rotation
  6271. },
  6272. quaternion: {
  6273. enumerable: true,
  6274. value: quaternion
  6275. },
  6276. scale: {
  6277. enumerable: true,
  6278. value: scale
  6279. },
  6280. modelViewMatrix: {
  6281. value: new Matrix4()
  6282. },
  6283. normalMatrix: {
  6284. value: new Matrix3()
  6285. }
  6286. } );
  6287. this.matrix = new Matrix4();
  6288. this.matrixWorld = new Matrix4();
  6289. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6290. this.matrixWorldNeedsUpdate = false;
  6291. this.layers = new Layers();
  6292. this.visible = true;
  6293. this.castShadow = false;
  6294. this.receiveShadow = false;
  6295. this.frustumCulled = true;
  6296. this.renderOrder = 0;
  6297. this.userData = {};
  6298. }
  6299. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6300. Object3D.DefaultMatrixAutoUpdate = true;
  6301. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6302. isObject3D: true,
  6303. applyMatrix: function ( matrix ) {
  6304. this.matrix.multiplyMatrices( matrix, this.matrix );
  6305. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6306. },
  6307. setRotationFromAxisAngle: function ( axis, angle ) {
  6308. // assumes axis is normalized
  6309. this.quaternion.setFromAxisAngle( axis, angle );
  6310. },
  6311. setRotationFromEuler: function ( euler ) {
  6312. this.quaternion.setFromEuler( euler, true );
  6313. },
  6314. setRotationFromMatrix: function ( m ) {
  6315. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6316. this.quaternion.setFromRotationMatrix( m );
  6317. },
  6318. setRotationFromQuaternion: function ( q ) {
  6319. // assumes q is normalized
  6320. this.quaternion.copy( q );
  6321. },
  6322. rotateOnAxis: function () {
  6323. // rotate object on axis in object space
  6324. // axis is assumed to be normalized
  6325. var q1 = new Quaternion();
  6326. return function rotateOnAxis( axis, angle ) {
  6327. q1.setFromAxisAngle( axis, angle );
  6328. this.quaternion.multiply( q1 );
  6329. return this;
  6330. };
  6331. }(),
  6332. rotateX: function () {
  6333. var v1 = new Vector3( 1, 0, 0 );
  6334. return function rotateX( angle ) {
  6335. return this.rotateOnAxis( v1, angle );
  6336. };
  6337. }(),
  6338. rotateY: function () {
  6339. var v1 = new Vector3( 0, 1, 0 );
  6340. return function rotateY( angle ) {
  6341. return this.rotateOnAxis( v1, angle );
  6342. };
  6343. }(),
  6344. rotateZ: function () {
  6345. var v1 = new Vector3( 0, 0, 1 );
  6346. return function rotateZ( angle ) {
  6347. return this.rotateOnAxis( v1, angle );
  6348. };
  6349. }(),
  6350. translateOnAxis: function () {
  6351. // translate object by distance along axis in object space
  6352. // axis is assumed to be normalized
  6353. var v1 = new Vector3();
  6354. return function translateOnAxis( axis, distance ) {
  6355. v1.copy( axis ).applyQuaternion( this.quaternion );
  6356. this.position.add( v1.multiplyScalar( distance ) );
  6357. return this;
  6358. };
  6359. }(),
  6360. translateX: function () {
  6361. var v1 = new Vector3( 1, 0, 0 );
  6362. return function translateX( distance ) {
  6363. return this.translateOnAxis( v1, distance );
  6364. };
  6365. }(),
  6366. translateY: function () {
  6367. var v1 = new Vector3( 0, 1, 0 );
  6368. return function translateY( distance ) {
  6369. return this.translateOnAxis( v1, distance );
  6370. };
  6371. }(),
  6372. translateZ: function () {
  6373. var v1 = new Vector3( 0, 0, 1 );
  6374. return function translateZ( distance ) {
  6375. return this.translateOnAxis( v1, distance );
  6376. };
  6377. }(),
  6378. localToWorld: function ( vector ) {
  6379. return vector.applyMatrix4( this.matrixWorld );
  6380. },
  6381. worldToLocal: function () {
  6382. var m1 = new Matrix4();
  6383. return function worldToLocal( vector ) {
  6384. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6385. };
  6386. }(),
  6387. lookAt: function () {
  6388. // This routine does not support objects with rotated and/or translated parent(s)
  6389. var m1 = new Matrix4();
  6390. return function lookAt( vector ) {
  6391. m1.lookAt( vector, this.position, this.up );
  6392. this.quaternion.setFromRotationMatrix( m1 );
  6393. };
  6394. }(),
  6395. add: function ( object ) {
  6396. if ( arguments.length > 1 ) {
  6397. for ( var i = 0; i < arguments.length; i ++ ) {
  6398. this.add( arguments[ i ] );
  6399. }
  6400. return this;
  6401. }
  6402. if ( object === this ) {
  6403. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6404. return this;
  6405. }
  6406. if ( (object && object.isObject3D) ) {
  6407. if ( object.parent !== null ) {
  6408. object.parent.remove( object );
  6409. }
  6410. object.parent = this;
  6411. object.dispatchEvent( { type: 'added' } );
  6412. this.children.push( object );
  6413. } else {
  6414. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6415. }
  6416. return this;
  6417. },
  6418. remove: function ( object ) {
  6419. if ( arguments.length > 1 ) {
  6420. for ( var i = 0; i < arguments.length; i ++ ) {
  6421. this.remove( arguments[ i ] );
  6422. }
  6423. }
  6424. var index = this.children.indexOf( object );
  6425. if ( index !== - 1 ) {
  6426. object.parent = null;
  6427. object.dispatchEvent( { type: 'removed' } );
  6428. this.children.splice( index, 1 );
  6429. }
  6430. },
  6431. getObjectById: function ( id ) {
  6432. return this.getObjectByProperty( 'id', id );
  6433. },
  6434. getObjectByName: function ( name ) {
  6435. return this.getObjectByProperty( 'name', name );
  6436. },
  6437. getObjectByProperty: function ( name, value ) {
  6438. if ( this[ name ] === value ) return this;
  6439. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6440. var child = this.children[ i ];
  6441. var object = child.getObjectByProperty( name, value );
  6442. if ( object !== undefined ) {
  6443. return object;
  6444. }
  6445. }
  6446. return undefined;
  6447. },
  6448. getWorldPosition: function ( optionalTarget ) {
  6449. var result = optionalTarget || new Vector3();
  6450. this.updateMatrixWorld( true );
  6451. return result.setFromMatrixPosition( this.matrixWorld );
  6452. },
  6453. getWorldQuaternion: function () {
  6454. var position = new Vector3();
  6455. var scale = new Vector3();
  6456. return function getWorldQuaternion( optionalTarget ) {
  6457. var result = optionalTarget || new Quaternion();
  6458. this.updateMatrixWorld( true );
  6459. this.matrixWorld.decompose( position, result, scale );
  6460. return result;
  6461. };
  6462. }(),
  6463. getWorldRotation: function () {
  6464. var quaternion = new Quaternion();
  6465. return function getWorldRotation( optionalTarget ) {
  6466. var result = optionalTarget || new Euler();
  6467. this.getWorldQuaternion( quaternion );
  6468. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6469. };
  6470. }(),
  6471. getWorldScale: function () {
  6472. var position = new Vector3();
  6473. var quaternion = new Quaternion();
  6474. return function getWorldScale( optionalTarget ) {
  6475. var result = optionalTarget || new Vector3();
  6476. this.updateMatrixWorld( true );
  6477. this.matrixWorld.decompose( position, quaternion, result );
  6478. return result;
  6479. };
  6480. }(),
  6481. getWorldDirection: function () {
  6482. var quaternion = new Quaternion();
  6483. return function getWorldDirection( optionalTarget ) {
  6484. var result = optionalTarget || new Vector3();
  6485. this.getWorldQuaternion( quaternion );
  6486. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6487. };
  6488. }(),
  6489. raycast: function () {},
  6490. traverse: function ( callback ) {
  6491. callback( this );
  6492. var children = this.children;
  6493. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6494. children[ i ].traverse( callback );
  6495. }
  6496. },
  6497. traverseVisible: function ( callback ) {
  6498. if ( this.visible === false ) return;
  6499. callback( this );
  6500. var children = this.children;
  6501. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6502. children[ i ].traverseVisible( callback );
  6503. }
  6504. },
  6505. traverseAncestors: function ( callback ) {
  6506. var parent = this.parent;
  6507. if ( parent !== null ) {
  6508. callback( parent );
  6509. parent.traverseAncestors( callback );
  6510. }
  6511. },
  6512. updateMatrix: function () {
  6513. this.matrix.compose( this.position, this.quaternion, this.scale );
  6514. this.matrixWorldNeedsUpdate = true;
  6515. },
  6516. updateMatrixWorld: function ( force ) {
  6517. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6518. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6519. if ( this.parent === null ) {
  6520. this.matrixWorld.copy( this.matrix );
  6521. } else {
  6522. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6523. }
  6524. this.matrixWorldNeedsUpdate = false;
  6525. force = true;
  6526. }
  6527. // update children
  6528. var children = this.children;
  6529. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6530. children[ i ].updateMatrixWorld( force );
  6531. }
  6532. },
  6533. toJSON: function ( meta ) {
  6534. // meta is '' when called from JSON.stringify
  6535. var isRootObject = ( meta === undefined || meta === '' );
  6536. var output = {};
  6537. // meta is a hash used to collect geometries, materials.
  6538. // not providing it implies that this is the root object
  6539. // being serialized.
  6540. if ( isRootObject ) {
  6541. // initialize meta obj
  6542. meta = {
  6543. geometries: {},
  6544. materials: {},
  6545. textures: {},
  6546. images: {}
  6547. };
  6548. output.metadata = {
  6549. version: 4.4,
  6550. type: 'Object',
  6551. generator: 'Object3D.toJSON'
  6552. };
  6553. }
  6554. // standard Object3D serialization
  6555. var object = {};
  6556. object.uuid = this.uuid;
  6557. object.type = this.type;
  6558. if ( this.name !== '' ) object.name = this.name;
  6559. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6560. if ( this.castShadow === true ) object.castShadow = true;
  6561. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6562. if ( this.visible === false ) object.visible = false;
  6563. object.matrix = this.matrix.toArray();
  6564. //
  6565. if ( this.geometry !== undefined ) {
  6566. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6567. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6568. }
  6569. object.geometry = this.geometry.uuid;
  6570. }
  6571. if ( this.material !== undefined ) {
  6572. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6573. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6574. }
  6575. object.material = this.material.uuid;
  6576. }
  6577. //
  6578. if ( this.children.length > 0 ) {
  6579. object.children = [];
  6580. for ( var i = 0; i < this.children.length; i ++ ) {
  6581. object.children.push( this.children[ i ].toJSON( meta ).object );
  6582. }
  6583. }
  6584. if ( isRootObject ) {
  6585. var geometries = extractFromCache( meta.geometries );
  6586. var materials = extractFromCache( meta.materials );
  6587. var textures = extractFromCache( meta.textures );
  6588. var images = extractFromCache( meta.images );
  6589. if ( geometries.length > 0 ) output.geometries = geometries;
  6590. if ( materials.length > 0 ) output.materials = materials;
  6591. if ( textures.length > 0 ) output.textures = textures;
  6592. if ( images.length > 0 ) output.images = images;
  6593. }
  6594. output.object = object;
  6595. return output;
  6596. // extract data from the cache hash
  6597. // remove metadata on each item
  6598. // and return as array
  6599. function extractFromCache( cache ) {
  6600. var values = [];
  6601. for ( var key in cache ) {
  6602. var data = cache[ key ];
  6603. delete data.metadata;
  6604. values.push( data );
  6605. }
  6606. return values;
  6607. }
  6608. },
  6609. clone: function ( recursive ) {
  6610. return new this.constructor().copy( this, recursive );
  6611. },
  6612. copy: function ( source, recursive ) {
  6613. if ( recursive === undefined ) recursive = true;
  6614. this.name = source.name;
  6615. this.up.copy( source.up );
  6616. this.position.copy( source.position );
  6617. this.quaternion.copy( source.quaternion );
  6618. this.scale.copy( source.scale );
  6619. this.matrix.copy( source.matrix );
  6620. this.matrixWorld.copy( source.matrixWorld );
  6621. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6622. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6623. this.visible = source.visible;
  6624. this.castShadow = source.castShadow;
  6625. this.receiveShadow = source.receiveShadow;
  6626. this.frustumCulled = source.frustumCulled;
  6627. this.renderOrder = source.renderOrder;
  6628. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6629. if ( recursive === true ) {
  6630. for ( var i = 0; i < source.children.length; i ++ ) {
  6631. var child = source.children[ i ];
  6632. this.add( child.clone() );
  6633. }
  6634. }
  6635. return this;
  6636. }
  6637. } );
  6638. var count$3 = 0;
  6639. function Object3DIdCount() { return count$3++; };
  6640. /**
  6641. * @author mrdoob / http://mrdoob.com/
  6642. * @author kile / http://kile.stravaganza.org/
  6643. * @author alteredq / http://alteredqualia.com/
  6644. * @author mikael emtinger / http://gomo.se/
  6645. * @author zz85 / http://www.lab4games.net/zz85/blog
  6646. * @author bhouston / http://clara.io
  6647. */
  6648. function Geometry() {
  6649. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6650. this.uuid = exports.Math.generateUUID();
  6651. this.name = '';
  6652. this.type = 'Geometry';
  6653. this.vertices = [];
  6654. this.colors = [];
  6655. this.faces = [];
  6656. this.faceVertexUvs = [ [] ];
  6657. this.morphTargets = [];
  6658. this.morphNormals = [];
  6659. this.skinWeights = [];
  6660. this.skinIndices = [];
  6661. this.lineDistances = [];
  6662. this.boundingBox = null;
  6663. this.boundingSphere = null;
  6664. // update flags
  6665. this.elementsNeedUpdate = false;
  6666. this.verticesNeedUpdate = false;
  6667. this.uvsNeedUpdate = false;
  6668. this.normalsNeedUpdate = false;
  6669. this.colorsNeedUpdate = false;
  6670. this.lineDistancesNeedUpdate = false;
  6671. this.groupsNeedUpdate = false;
  6672. }
  6673. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6674. isGeometry: true,
  6675. applyMatrix: function ( matrix ) {
  6676. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6677. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6678. var vertex = this.vertices[ i ];
  6679. vertex.applyMatrix4( matrix );
  6680. }
  6681. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6682. var face = this.faces[ i ];
  6683. face.normal.applyMatrix3( normalMatrix ).normalize();
  6684. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6685. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6686. }
  6687. }
  6688. if ( this.boundingBox !== null ) {
  6689. this.computeBoundingBox();
  6690. }
  6691. if ( this.boundingSphere !== null ) {
  6692. this.computeBoundingSphere();
  6693. }
  6694. this.verticesNeedUpdate = true;
  6695. this.normalsNeedUpdate = true;
  6696. return this;
  6697. },
  6698. rotateX: function () {
  6699. // rotate geometry around world x-axis
  6700. var m1;
  6701. return function rotateX( angle ) {
  6702. if ( m1 === undefined ) m1 = new Matrix4();
  6703. m1.makeRotationX( angle );
  6704. this.applyMatrix( m1 );
  6705. return this;
  6706. };
  6707. }(),
  6708. rotateY: function () {
  6709. // rotate geometry around world y-axis
  6710. var m1;
  6711. return function rotateY( angle ) {
  6712. if ( m1 === undefined ) m1 = new Matrix4();
  6713. m1.makeRotationY( angle );
  6714. this.applyMatrix( m1 );
  6715. return this;
  6716. };
  6717. }(),
  6718. rotateZ: function () {
  6719. // rotate geometry around world z-axis
  6720. var m1;
  6721. return function rotateZ( angle ) {
  6722. if ( m1 === undefined ) m1 = new Matrix4();
  6723. m1.makeRotationZ( angle );
  6724. this.applyMatrix( m1 );
  6725. return this;
  6726. };
  6727. }(),
  6728. translate: function () {
  6729. // translate geometry
  6730. var m1;
  6731. return function translate( x, y, z ) {
  6732. if ( m1 === undefined ) m1 = new Matrix4();
  6733. m1.makeTranslation( x, y, z );
  6734. this.applyMatrix( m1 );
  6735. return this;
  6736. };
  6737. }(),
  6738. scale: function () {
  6739. // scale geometry
  6740. var m1;
  6741. return function scale( x, y, z ) {
  6742. if ( m1 === undefined ) m1 = new Matrix4();
  6743. m1.makeScale( x, y, z );
  6744. this.applyMatrix( m1 );
  6745. return this;
  6746. };
  6747. }(),
  6748. lookAt: function () {
  6749. var obj;
  6750. return function lookAt( vector ) {
  6751. if ( obj === undefined ) obj = new Object3D();
  6752. obj.lookAt( vector );
  6753. obj.updateMatrix();
  6754. this.applyMatrix( obj.matrix );
  6755. };
  6756. }(),
  6757. fromBufferGeometry: function ( geometry ) {
  6758. var scope = this;
  6759. var indices = geometry.index !== null ? geometry.index.array : undefined;
  6760. var attributes = geometry.attributes;
  6761. var positions = attributes.position.array;
  6762. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  6763. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  6764. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  6765. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  6766. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  6767. var tempNormals = [];
  6768. var tempUVs = [];
  6769. var tempUVs2 = [];
  6770. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  6771. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  6772. if ( normals !== undefined ) {
  6773. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  6774. }
  6775. if ( colors !== undefined ) {
  6776. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  6777. }
  6778. if ( uvs !== undefined ) {
  6779. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  6780. }
  6781. if ( uvs2 !== undefined ) {
  6782. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  6783. }
  6784. }
  6785. function addFace( a, b, c, materialIndex ) {
  6786. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  6787. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  6788. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  6789. scope.faces.push( face );
  6790. if ( uvs !== undefined ) {
  6791. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  6792. }
  6793. if ( uvs2 !== undefined ) {
  6794. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  6795. }
  6796. }
  6797. if ( indices !== undefined ) {
  6798. var groups = geometry.groups;
  6799. if ( groups.length > 0 ) {
  6800. for ( var i = 0; i < groups.length; i ++ ) {
  6801. var group = groups[ i ];
  6802. var start = group.start;
  6803. var count = group.count;
  6804. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  6805. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  6806. }
  6807. }
  6808. } else {
  6809. for ( var i = 0; i < indices.length; i += 3 ) {
  6810. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  6811. }
  6812. }
  6813. } else {
  6814. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  6815. addFace( i, i + 1, i + 2 );
  6816. }
  6817. }
  6818. this.computeFaceNormals();
  6819. if ( geometry.boundingBox !== null ) {
  6820. this.boundingBox = geometry.boundingBox.clone();
  6821. }
  6822. if ( geometry.boundingSphere !== null ) {
  6823. this.boundingSphere = geometry.boundingSphere.clone();
  6824. }
  6825. return this;
  6826. },
  6827. center: function () {
  6828. this.computeBoundingBox();
  6829. var offset = this.boundingBox.center().negate();
  6830. this.translate( offset.x, offset.y, offset.z );
  6831. return offset;
  6832. },
  6833. normalize: function () {
  6834. this.computeBoundingSphere();
  6835. var center = this.boundingSphere.center;
  6836. var radius = this.boundingSphere.radius;
  6837. var s = radius === 0 ? 1 : 1.0 / radius;
  6838. var matrix = new Matrix4();
  6839. matrix.set(
  6840. s, 0, 0, - s * center.x,
  6841. 0, s, 0, - s * center.y,
  6842. 0, 0, s, - s * center.z,
  6843. 0, 0, 0, 1
  6844. );
  6845. this.applyMatrix( matrix );
  6846. return this;
  6847. },
  6848. computeFaceNormals: function () {
  6849. var cb = new Vector3(), ab = new Vector3();
  6850. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6851. var face = this.faces[ f ];
  6852. var vA = this.vertices[ face.a ];
  6853. var vB = this.vertices[ face.b ];
  6854. var vC = this.vertices[ face.c ];
  6855. cb.subVectors( vC, vB );
  6856. ab.subVectors( vA, vB );
  6857. cb.cross( ab );
  6858. cb.normalize();
  6859. face.normal.copy( cb );
  6860. }
  6861. },
  6862. computeVertexNormals: function ( areaWeighted ) {
  6863. if ( areaWeighted === undefined ) areaWeighted = true;
  6864. var v, vl, f, fl, face, vertices;
  6865. vertices = new Array( this.vertices.length );
  6866. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6867. vertices[ v ] = new Vector3();
  6868. }
  6869. if ( areaWeighted ) {
  6870. // vertex normals weighted by triangle areas
  6871. // http://www.iquilezles.org/www/articles/normals/normals.htm
  6872. var vA, vB, vC;
  6873. var cb = new Vector3(), ab = new Vector3();
  6874. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6875. face = this.faces[ f ];
  6876. vA = this.vertices[ face.a ];
  6877. vB = this.vertices[ face.b ];
  6878. vC = this.vertices[ face.c ];
  6879. cb.subVectors( vC, vB );
  6880. ab.subVectors( vA, vB );
  6881. cb.cross( ab );
  6882. vertices[ face.a ].add( cb );
  6883. vertices[ face.b ].add( cb );
  6884. vertices[ face.c ].add( cb );
  6885. }
  6886. } else {
  6887. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6888. face = this.faces[ f ];
  6889. vertices[ face.a ].add( face.normal );
  6890. vertices[ face.b ].add( face.normal );
  6891. vertices[ face.c ].add( face.normal );
  6892. }
  6893. }
  6894. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6895. vertices[ v ].normalize();
  6896. }
  6897. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6898. face = this.faces[ f ];
  6899. var vertexNormals = face.vertexNormals;
  6900. if ( vertexNormals.length === 3 ) {
  6901. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  6902. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  6903. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  6904. } else {
  6905. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6906. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6907. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6908. }
  6909. }
  6910. if ( this.faces.length > 0 ) {
  6911. this.normalsNeedUpdate = true;
  6912. }
  6913. },
  6914. computeMorphNormals: function () {
  6915. var i, il, f, fl, face;
  6916. // save original normals
  6917. // - create temp variables on first access
  6918. // otherwise just copy (for faster repeated calls)
  6919. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6920. face = this.faces[ f ];
  6921. if ( ! face.__originalFaceNormal ) {
  6922. face.__originalFaceNormal = face.normal.clone();
  6923. } else {
  6924. face.__originalFaceNormal.copy( face.normal );
  6925. }
  6926. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6927. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6928. if ( ! face.__originalVertexNormals[ i ] ) {
  6929. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6930. } else {
  6931. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6932. }
  6933. }
  6934. }
  6935. // use temp geometry to compute face and vertex normals for each morph
  6936. var tmpGeo = new Geometry();
  6937. tmpGeo.faces = this.faces;
  6938. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6939. // create on first access
  6940. if ( ! this.morphNormals[ i ] ) {
  6941. this.morphNormals[ i ] = {};
  6942. this.morphNormals[ i ].faceNormals = [];
  6943. this.morphNormals[ i ].vertexNormals = [];
  6944. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6945. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6946. var faceNormal, vertexNormals;
  6947. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6948. faceNormal = new Vector3();
  6949. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  6950. dstNormalsFace.push( faceNormal );
  6951. dstNormalsVertex.push( vertexNormals );
  6952. }
  6953. }
  6954. var morphNormals = this.morphNormals[ i ];
  6955. // set vertices to morph target
  6956. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6957. // compute morph normals
  6958. tmpGeo.computeFaceNormals();
  6959. tmpGeo.computeVertexNormals();
  6960. // store morph normals
  6961. var faceNormal, vertexNormals;
  6962. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6963. face = this.faces[ f ];
  6964. faceNormal = morphNormals.faceNormals[ f ];
  6965. vertexNormals = morphNormals.vertexNormals[ f ];
  6966. faceNormal.copy( face.normal );
  6967. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6968. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6969. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6970. }
  6971. }
  6972. // restore original normals
  6973. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6974. face = this.faces[ f ];
  6975. face.normal = face.__originalFaceNormal;
  6976. face.vertexNormals = face.__originalVertexNormals;
  6977. }
  6978. },
  6979. computeTangents: function () {
  6980. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  6981. },
  6982. computeLineDistances: function () {
  6983. var d = 0;
  6984. var vertices = this.vertices;
  6985. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6986. if ( i > 0 ) {
  6987. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6988. }
  6989. this.lineDistances[ i ] = d;
  6990. }
  6991. },
  6992. computeBoundingBox: function () {
  6993. if ( this.boundingBox === null ) {
  6994. this.boundingBox = new Box3();
  6995. }
  6996. this.boundingBox.setFromPoints( this.vertices );
  6997. },
  6998. computeBoundingSphere: function () {
  6999. if ( this.boundingSphere === null ) {
  7000. this.boundingSphere = new Sphere();
  7001. }
  7002. this.boundingSphere.setFromPoints( this.vertices );
  7003. },
  7004. merge: function ( geometry, matrix, materialIndexOffset ) {
  7005. if ( (geometry && geometry.isGeometry) === false ) {
  7006. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7007. return;
  7008. }
  7009. var normalMatrix,
  7010. vertexOffset = this.vertices.length,
  7011. vertices1 = this.vertices,
  7012. vertices2 = geometry.vertices,
  7013. faces1 = this.faces,
  7014. faces2 = geometry.faces,
  7015. uvs1 = this.faceVertexUvs[ 0 ],
  7016. uvs2 = geometry.faceVertexUvs[ 0 ];
  7017. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7018. if ( matrix !== undefined ) {
  7019. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7020. }
  7021. // vertices
  7022. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7023. var vertex = vertices2[ i ];
  7024. var vertexCopy = vertex.clone();
  7025. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7026. vertices1.push( vertexCopy );
  7027. }
  7028. // faces
  7029. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7030. var face = faces2[ i ], faceCopy, normal, color,
  7031. faceVertexNormals = face.vertexNormals,
  7032. faceVertexColors = face.vertexColors;
  7033. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7034. faceCopy.normal.copy( face.normal );
  7035. if ( normalMatrix !== undefined ) {
  7036. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7037. }
  7038. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7039. normal = faceVertexNormals[ j ].clone();
  7040. if ( normalMatrix !== undefined ) {
  7041. normal.applyMatrix3( normalMatrix ).normalize();
  7042. }
  7043. faceCopy.vertexNormals.push( normal );
  7044. }
  7045. faceCopy.color.copy( face.color );
  7046. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7047. color = faceVertexColors[ j ];
  7048. faceCopy.vertexColors.push( color.clone() );
  7049. }
  7050. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7051. faces1.push( faceCopy );
  7052. }
  7053. // uvs
  7054. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7055. var uv = uvs2[ i ], uvCopy = [];
  7056. if ( uv === undefined ) {
  7057. continue;
  7058. }
  7059. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7060. uvCopy.push( uv[ j ].clone() );
  7061. }
  7062. uvs1.push( uvCopy );
  7063. }
  7064. },
  7065. mergeMesh: function ( mesh ) {
  7066. if ( (mesh && mesh.isMesh) === false ) {
  7067. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7068. return;
  7069. }
  7070. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7071. this.merge( mesh.geometry, mesh.matrix );
  7072. },
  7073. /*
  7074. * Checks for duplicate vertices with hashmap.
  7075. * Duplicated vertices are removed
  7076. * and faces' vertices are updated.
  7077. */
  7078. mergeVertices: function () {
  7079. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7080. var unique = [], changes = [];
  7081. var v, key;
  7082. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7083. var precision = Math.pow( 10, precisionPoints );
  7084. var i, il, face;
  7085. var indices, j, jl;
  7086. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7087. v = this.vertices[ i ];
  7088. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7089. if ( verticesMap[ key ] === undefined ) {
  7090. verticesMap[ key ] = i;
  7091. unique.push( this.vertices[ i ] );
  7092. changes[ i ] = unique.length - 1;
  7093. } else {
  7094. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7095. changes[ i ] = changes[ verticesMap[ key ] ];
  7096. }
  7097. }
  7098. // if faces are completely degenerate after merging vertices, we
  7099. // have to remove them from the geometry.
  7100. var faceIndicesToRemove = [];
  7101. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7102. face = this.faces[ i ];
  7103. face.a = changes[ face.a ];
  7104. face.b = changes[ face.b ];
  7105. face.c = changes[ face.c ];
  7106. indices = [ face.a, face.b, face.c ];
  7107. var dupIndex = - 1;
  7108. // if any duplicate vertices are found in a Face3
  7109. // we have to remove the face as nothing can be saved
  7110. for ( var n = 0; n < 3; n ++ ) {
  7111. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7112. dupIndex = n;
  7113. faceIndicesToRemove.push( i );
  7114. break;
  7115. }
  7116. }
  7117. }
  7118. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7119. var idx = faceIndicesToRemove[ i ];
  7120. this.faces.splice( idx, 1 );
  7121. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7122. this.faceVertexUvs[ j ].splice( idx, 1 );
  7123. }
  7124. }
  7125. // Use unique set of vertices
  7126. var diff = this.vertices.length - unique.length;
  7127. this.vertices = unique;
  7128. return diff;
  7129. },
  7130. sortFacesByMaterialIndex: function () {
  7131. var faces = this.faces;
  7132. var length = faces.length;
  7133. // tag faces
  7134. for ( var i = 0; i < length; i ++ ) {
  7135. faces[ i ]._id = i;
  7136. }
  7137. // sort faces
  7138. function materialIndexSort( a, b ) {
  7139. return a.materialIndex - b.materialIndex;
  7140. }
  7141. faces.sort( materialIndexSort );
  7142. // sort uvs
  7143. var uvs1 = this.faceVertexUvs[ 0 ];
  7144. var uvs2 = this.faceVertexUvs[ 1 ];
  7145. var newUvs1, newUvs2;
  7146. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7147. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7148. for ( var i = 0; i < length; i ++ ) {
  7149. var id = faces[ i ]._id;
  7150. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7151. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7152. }
  7153. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7154. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7155. },
  7156. toJSON: function () {
  7157. var data = {
  7158. metadata: {
  7159. version: 4.4,
  7160. type: 'Geometry',
  7161. generator: 'Geometry.toJSON'
  7162. }
  7163. };
  7164. // standard Geometry serialization
  7165. data.uuid = this.uuid;
  7166. data.type = this.type;
  7167. if ( this.name !== '' ) data.name = this.name;
  7168. if ( this.parameters !== undefined ) {
  7169. var parameters = this.parameters;
  7170. for ( var key in parameters ) {
  7171. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7172. }
  7173. return data;
  7174. }
  7175. var vertices = [];
  7176. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7177. var vertex = this.vertices[ i ];
  7178. vertices.push( vertex.x, vertex.y, vertex.z );
  7179. }
  7180. var faces = [];
  7181. var normals = [];
  7182. var normalsHash = {};
  7183. var colors = [];
  7184. var colorsHash = {};
  7185. var uvs = [];
  7186. var uvsHash = {};
  7187. for ( var i = 0; i < this.faces.length; i ++ ) {
  7188. var face = this.faces[ i ];
  7189. var hasMaterial = true;
  7190. var hasFaceUv = false; // deprecated
  7191. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7192. var hasFaceNormal = face.normal.length() > 0;
  7193. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7194. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7195. var hasFaceVertexColor = face.vertexColors.length > 0;
  7196. var faceType = 0;
  7197. faceType = setBit( faceType, 0, 0 ); // isQuad
  7198. faceType = setBit( faceType, 1, hasMaterial );
  7199. faceType = setBit( faceType, 2, hasFaceUv );
  7200. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7201. faceType = setBit( faceType, 4, hasFaceNormal );
  7202. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7203. faceType = setBit( faceType, 6, hasFaceColor );
  7204. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7205. faces.push( faceType );
  7206. faces.push( face.a, face.b, face.c );
  7207. faces.push( face.materialIndex );
  7208. if ( hasFaceVertexUv ) {
  7209. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7210. faces.push(
  7211. getUvIndex( faceVertexUvs[ 0 ] ),
  7212. getUvIndex( faceVertexUvs[ 1 ] ),
  7213. getUvIndex( faceVertexUvs[ 2 ] )
  7214. );
  7215. }
  7216. if ( hasFaceNormal ) {
  7217. faces.push( getNormalIndex( face.normal ) );
  7218. }
  7219. if ( hasFaceVertexNormal ) {
  7220. var vertexNormals = face.vertexNormals;
  7221. faces.push(
  7222. getNormalIndex( vertexNormals[ 0 ] ),
  7223. getNormalIndex( vertexNormals[ 1 ] ),
  7224. getNormalIndex( vertexNormals[ 2 ] )
  7225. );
  7226. }
  7227. if ( hasFaceColor ) {
  7228. faces.push( getColorIndex( face.color ) );
  7229. }
  7230. if ( hasFaceVertexColor ) {
  7231. var vertexColors = face.vertexColors;
  7232. faces.push(
  7233. getColorIndex( vertexColors[ 0 ] ),
  7234. getColorIndex( vertexColors[ 1 ] ),
  7235. getColorIndex( vertexColors[ 2 ] )
  7236. );
  7237. }
  7238. }
  7239. function setBit( value, position, enabled ) {
  7240. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7241. }
  7242. function getNormalIndex( normal ) {
  7243. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7244. if ( normalsHash[ hash ] !== undefined ) {
  7245. return normalsHash[ hash ];
  7246. }
  7247. normalsHash[ hash ] = normals.length / 3;
  7248. normals.push( normal.x, normal.y, normal.z );
  7249. return normalsHash[ hash ];
  7250. }
  7251. function getColorIndex( color ) {
  7252. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7253. if ( colorsHash[ hash ] !== undefined ) {
  7254. return colorsHash[ hash ];
  7255. }
  7256. colorsHash[ hash ] = colors.length;
  7257. colors.push( color.getHex() );
  7258. return colorsHash[ hash ];
  7259. }
  7260. function getUvIndex( uv ) {
  7261. var hash = uv.x.toString() + uv.y.toString();
  7262. if ( uvsHash[ hash ] !== undefined ) {
  7263. return uvsHash[ hash ];
  7264. }
  7265. uvsHash[ hash ] = uvs.length / 2;
  7266. uvs.push( uv.x, uv.y );
  7267. return uvsHash[ hash ];
  7268. }
  7269. data.data = {};
  7270. data.data.vertices = vertices;
  7271. data.data.normals = normals;
  7272. if ( colors.length > 0 ) data.data.colors = colors;
  7273. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7274. data.data.faces = faces;
  7275. return data;
  7276. },
  7277. clone: function () {
  7278. /*
  7279. // Handle primitives
  7280. var parameters = this.parameters;
  7281. if ( parameters !== undefined ) {
  7282. var values = [];
  7283. for ( var key in parameters ) {
  7284. values.push( parameters[ key ] );
  7285. }
  7286. var geometry = Object.create( this.constructor.prototype );
  7287. this.constructor.apply( geometry, values );
  7288. return geometry;
  7289. }
  7290. return new this.constructor().copy( this );
  7291. */
  7292. return new Geometry().copy( this );
  7293. },
  7294. copy: function ( source ) {
  7295. this.vertices = [];
  7296. this.faces = [];
  7297. this.faceVertexUvs = [ [] ];
  7298. var vertices = source.vertices;
  7299. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7300. this.vertices.push( vertices[ i ].clone() );
  7301. }
  7302. var faces = source.faces;
  7303. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  7304. this.faces.push( faces[ i ].clone() );
  7305. }
  7306. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7307. var faceVertexUvs = source.faceVertexUvs[ i ];
  7308. if ( this.faceVertexUvs[ i ] === undefined ) {
  7309. this.faceVertexUvs[ i ] = [];
  7310. }
  7311. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7312. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7313. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  7314. var uv = uvs[ k ];
  7315. uvsCopy.push( uv.clone() );
  7316. }
  7317. this.faceVertexUvs[ i ].push( uvsCopy );
  7318. }
  7319. }
  7320. return this;
  7321. },
  7322. dispose: function () {
  7323. this.dispatchEvent( { type: 'dispose' } );
  7324. }
  7325. } );
  7326. var count$2 = 0;
  7327. function GeometryIdCount() { return count$2++; };
  7328. /**
  7329. * @author mrdoob / http://mrdoob.com/
  7330. */
  7331. function DirectGeometry() {
  7332. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7333. this.uuid = exports.Math.generateUUID();
  7334. this.name = '';
  7335. this.type = 'DirectGeometry';
  7336. this.indices = [];
  7337. this.vertices = [];
  7338. this.normals = [];
  7339. this.colors = [];
  7340. this.uvs = [];
  7341. this.uvs2 = [];
  7342. this.groups = [];
  7343. this.morphTargets = {};
  7344. this.skinWeights = [];
  7345. this.skinIndices = [];
  7346. // this.lineDistances = [];
  7347. this.boundingBox = null;
  7348. this.boundingSphere = null;
  7349. // update flags
  7350. this.verticesNeedUpdate = false;
  7351. this.normalsNeedUpdate = false;
  7352. this.colorsNeedUpdate = false;
  7353. this.uvsNeedUpdate = false;
  7354. this.groupsNeedUpdate = false;
  7355. }
  7356. Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, {
  7357. computeBoundingBox: Geometry.prototype.computeBoundingBox,
  7358. computeBoundingSphere: Geometry.prototype.computeBoundingSphere,
  7359. computeFaceNormals: function () {
  7360. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  7361. },
  7362. computeVertexNormals: function () {
  7363. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  7364. },
  7365. computeGroups: function ( geometry ) {
  7366. var group;
  7367. var groups = [];
  7368. var materialIndex;
  7369. var faces = geometry.faces;
  7370. for ( var i = 0; i < faces.length; i ++ ) {
  7371. var face = faces[ i ];
  7372. // materials
  7373. if ( face.materialIndex !== materialIndex ) {
  7374. materialIndex = face.materialIndex;
  7375. if ( group !== undefined ) {
  7376. group.count = ( i * 3 ) - group.start;
  7377. groups.push( group );
  7378. }
  7379. group = {
  7380. start: i * 3,
  7381. materialIndex: materialIndex
  7382. };
  7383. }
  7384. }
  7385. if ( group !== undefined ) {
  7386. group.count = ( i * 3 ) - group.start;
  7387. groups.push( group );
  7388. }
  7389. this.groups = groups;
  7390. },
  7391. fromGeometry: function ( geometry ) {
  7392. var faces = geometry.faces;
  7393. var vertices = geometry.vertices;
  7394. var faceVertexUvs = geometry.faceVertexUvs;
  7395. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7396. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7397. // morphs
  7398. var morphTargets = geometry.morphTargets;
  7399. var morphTargetsLength = morphTargets.length;
  7400. var morphTargetsPosition;
  7401. if ( morphTargetsLength > 0 ) {
  7402. morphTargetsPosition = [];
  7403. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7404. morphTargetsPosition[ i ] = [];
  7405. }
  7406. this.morphTargets.position = morphTargetsPosition;
  7407. }
  7408. var morphNormals = geometry.morphNormals;
  7409. var morphNormalsLength = morphNormals.length;
  7410. var morphTargetsNormal;
  7411. if ( morphNormalsLength > 0 ) {
  7412. morphTargetsNormal = [];
  7413. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7414. morphTargetsNormal[ i ] = [];
  7415. }
  7416. this.morphTargets.normal = morphTargetsNormal;
  7417. }
  7418. // skins
  7419. var skinIndices = geometry.skinIndices;
  7420. var skinWeights = geometry.skinWeights;
  7421. var hasSkinIndices = skinIndices.length === vertices.length;
  7422. var hasSkinWeights = skinWeights.length === vertices.length;
  7423. //
  7424. for ( var i = 0; i < faces.length; i ++ ) {
  7425. var face = faces[ i ];
  7426. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7427. var vertexNormals = face.vertexNormals;
  7428. if ( vertexNormals.length === 3 ) {
  7429. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7430. } else {
  7431. var normal = face.normal;
  7432. this.normals.push( normal, normal, normal );
  7433. }
  7434. var vertexColors = face.vertexColors;
  7435. if ( vertexColors.length === 3 ) {
  7436. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7437. } else {
  7438. var color = face.color;
  7439. this.colors.push( color, color, color );
  7440. }
  7441. if ( hasFaceVertexUv === true ) {
  7442. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7443. if ( vertexUvs !== undefined ) {
  7444. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7445. } else {
  7446. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7447. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7448. }
  7449. }
  7450. if ( hasFaceVertexUv2 === true ) {
  7451. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7452. if ( vertexUvs !== undefined ) {
  7453. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7454. } else {
  7455. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7456. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7457. }
  7458. }
  7459. // morphs
  7460. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7461. var morphTarget = morphTargets[ j ].vertices;
  7462. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7463. }
  7464. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7465. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7466. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7467. }
  7468. // skins
  7469. if ( hasSkinIndices ) {
  7470. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7471. }
  7472. if ( hasSkinWeights ) {
  7473. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7474. }
  7475. }
  7476. this.computeGroups( geometry );
  7477. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7478. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7479. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7480. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7481. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7482. return this;
  7483. },
  7484. dispose: function () {
  7485. this.dispatchEvent( { type: 'dispose' } );
  7486. }
  7487. } );
  7488. /**
  7489. * @author alteredq / http://alteredqualia.com/
  7490. * @author mrdoob / http://mrdoob.com/
  7491. */
  7492. function BufferGeometry() {
  7493. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7494. this.uuid = exports.Math.generateUUID();
  7495. this.name = '';
  7496. this.type = 'BufferGeometry';
  7497. this.index = null;
  7498. this.attributes = {};
  7499. this.morphAttributes = {};
  7500. this.groups = [];
  7501. this.boundingBox = null;
  7502. this.boundingSphere = null;
  7503. this.drawRange = { start: 0, count: Infinity };
  7504. }
  7505. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  7506. isBufferGeometry: true,
  7507. getIndex: function () {
  7508. return this.index;
  7509. },
  7510. setIndex: function ( index ) {
  7511. this.index = index;
  7512. },
  7513. addAttribute: function ( name, attribute ) {
  7514. if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) {
  7515. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  7516. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  7517. return;
  7518. }
  7519. if ( name === 'index' ) {
  7520. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  7521. this.setIndex( attribute );
  7522. return;
  7523. }
  7524. this.attributes[ name ] = attribute;
  7525. return this;
  7526. },
  7527. getAttribute: function ( name ) {
  7528. return this.attributes[ name ];
  7529. },
  7530. removeAttribute: function ( name ) {
  7531. delete this.attributes[ name ];
  7532. return this;
  7533. },
  7534. addGroup: function ( start, count, materialIndex ) {
  7535. this.groups.push( {
  7536. start: start,
  7537. count: count,
  7538. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7539. } );
  7540. },
  7541. clearGroups: function () {
  7542. this.groups = [];
  7543. },
  7544. setDrawRange: function ( start, count ) {
  7545. this.drawRange.start = start;
  7546. this.drawRange.count = count;
  7547. },
  7548. applyMatrix: function ( matrix ) {
  7549. var position = this.attributes.position;
  7550. if ( position !== undefined ) {
  7551. matrix.applyToVector3Array( position.array );
  7552. position.needsUpdate = true;
  7553. }
  7554. var normal = this.attributes.normal;
  7555. if ( normal !== undefined ) {
  7556. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7557. normalMatrix.applyToVector3Array( normal.array );
  7558. normal.needsUpdate = true;
  7559. }
  7560. if ( this.boundingBox !== null ) {
  7561. this.computeBoundingBox();
  7562. }
  7563. if ( this.boundingSphere !== null ) {
  7564. this.computeBoundingSphere();
  7565. }
  7566. return this;
  7567. },
  7568. rotateX: function () {
  7569. // rotate geometry around world x-axis
  7570. var m1;
  7571. return function rotateX( angle ) {
  7572. if ( m1 === undefined ) m1 = new Matrix4();
  7573. m1.makeRotationX( angle );
  7574. this.applyMatrix( m1 );
  7575. return this;
  7576. };
  7577. }(),
  7578. rotateY: function () {
  7579. // rotate geometry around world y-axis
  7580. var m1;
  7581. return function rotateY( angle ) {
  7582. if ( m1 === undefined ) m1 = new Matrix4();
  7583. m1.makeRotationY( angle );
  7584. this.applyMatrix( m1 );
  7585. return this;
  7586. };
  7587. }(),
  7588. rotateZ: function () {
  7589. // rotate geometry around world z-axis
  7590. var m1;
  7591. return function rotateZ( angle ) {
  7592. if ( m1 === undefined ) m1 = new Matrix4();
  7593. m1.makeRotationZ( angle );
  7594. this.applyMatrix( m1 );
  7595. return this;
  7596. };
  7597. }(),
  7598. translate: function () {
  7599. // translate geometry
  7600. var m1;
  7601. return function translate( x, y, z ) {
  7602. if ( m1 === undefined ) m1 = new Matrix4();
  7603. m1.makeTranslation( x, y, z );
  7604. this.applyMatrix( m1 );
  7605. return this;
  7606. };
  7607. }(),
  7608. scale: function () {
  7609. // scale geometry
  7610. var m1;
  7611. return function scale( x, y, z ) {
  7612. if ( m1 === undefined ) m1 = new Matrix4();
  7613. m1.makeScale( x, y, z );
  7614. this.applyMatrix( m1 );
  7615. return this;
  7616. };
  7617. }(),
  7618. lookAt: function () {
  7619. var obj;
  7620. return function lookAt( vector ) {
  7621. if ( obj === undefined ) obj = new Object3D();
  7622. obj.lookAt( vector );
  7623. obj.updateMatrix();
  7624. this.applyMatrix( obj.matrix );
  7625. };
  7626. }(),
  7627. center: function () {
  7628. this.computeBoundingBox();
  7629. var offset = this.boundingBox.center().negate();
  7630. this.translate( offset.x, offset.y, offset.z );
  7631. return offset;
  7632. },
  7633. setFromObject: function ( object ) {
  7634. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7635. var geometry = object.geometry;
  7636. if ( (object && object.isPoints) || (object && object.isLine) ) {
  7637. var positions = new Float32Attribute( geometry.vertices.length * 3, 3 );
  7638. var colors = new Float32Attribute( geometry.colors.length * 3, 3 );
  7639. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  7640. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  7641. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  7642. var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 );
  7643. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  7644. }
  7645. if ( geometry.boundingSphere !== null ) {
  7646. this.boundingSphere = geometry.boundingSphere.clone();
  7647. }
  7648. if ( geometry.boundingBox !== null ) {
  7649. this.boundingBox = geometry.boundingBox.clone();
  7650. }
  7651. } else if ( (object && object.isMesh) ) {
  7652. if ( (geometry && geometry.isGeometry) ) {
  7653. this.fromGeometry( geometry );
  7654. }
  7655. }
  7656. return this;
  7657. },
  7658. updateFromObject: function ( object ) {
  7659. var geometry = object.geometry;
  7660. if ( (object && object.isMesh) ) {
  7661. var direct = geometry.__directGeometry;
  7662. if ( geometry.elementsNeedUpdate === true ) {
  7663. direct = undefined;
  7664. geometry.elementsNeedUpdate = false;
  7665. }
  7666. if ( direct === undefined ) {
  7667. return this.fromGeometry( geometry );
  7668. }
  7669. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7670. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7671. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7672. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7673. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7674. geometry.verticesNeedUpdate = false;
  7675. geometry.normalsNeedUpdate = false;
  7676. geometry.colorsNeedUpdate = false;
  7677. geometry.uvsNeedUpdate = false;
  7678. geometry.groupsNeedUpdate = false;
  7679. geometry = direct;
  7680. }
  7681. var attribute;
  7682. if ( geometry.verticesNeedUpdate === true ) {
  7683. attribute = this.attributes.position;
  7684. if ( attribute !== undefined ) {
  7685. attribute.copyVector3sArray( geometry.vertices );
  7686. attribute.needsUpdate = true;
  7687. }
  7688. geometry.verticesNeedUpdate = false;
  7689. }
  7690. if ( geometry.normalsNeedUpdate === true ) {
  7691. attribute = this.attributes.normal;
  7692. if ( attribute !== undefined ) {
  7693. attribute.copyVector3sArray( geometry.normals );
  7694. attribute.needsUpdate = true;
  7695. }
  7696. geometry.normalsNeedUpdate = false;
  7697. }
  7698. if ( geometry.colorsNeedUpdate === true ) {
  7699. attribute = this.attributes.color;
  7700. if ( attribute !== undefined ) {
  7701. attribute.copyColorsArray( geometry.colors );
  7702. attribute.needsUpdate = true;
  7703. }
  7704. geometry.colorsNeedUpdate = false;
  7705. }
  7706. if ( geometry.uvsNeedUpdate ) {
  7707. attribute = this.attributes.uv;
  7708. if ( attribute !== undefined ) {
  7709. attribute.copyVector2sArray( geometry.uvs );
  7710. attribute.needsUpdate = true;
  7711. }
  7712. geometry.uvsNeedUpdate = false;
  7713. }
  7714. if ( geometry.lineDistancesNeedUpdate ) {
  7715. attribute = this.attributes.lineDistance;
  7716. if ( attribute !== undefined ) {
  7717. attribute.copyArray( geometry.lineDistances );
  7718. attribute.needsUpdate = true;
  7719. }
  7720. geometry.lineDistancesNeedUpdate = false;
  7721. }
  7722. if ( geometry.groupsNeedUpdate ) {
  7723. geometry.computeGroups( object.geometry );
  7724. this.groups = geometry.groups;
  7725. geometry.groupsNeedUpdate = false;
  7726. }
  7727. return this;
  7728. },
  7729. fromGeometry: function ( geometry ) {
  7730. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  7731. return this.fromDirectGeometry( geometry.__directGeometry );
  7732. },
  7733. fromDirectGeometry: function ( geometry ) {
  7734. var positions = new Float32Array( geometry.vertices.length * 3 );
  7735. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  7736. if ( geometry.normals.length > 0 ) {
  7737. var normals = new Float32Array( geometry.normals.length * 3 );
  7738. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  7739. }
  7740. if ( geometry.colors.length > 0 ) {
  7741. var colors = new Float32Array( geometry.colors.length * 3 );
  7742. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  7743. }
  7744. if ( geometry.uvs.length > 0 ) {
  7745. var uvs = new Float32Array( geometry.uvs.length * 2 );
  7746. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  7747. }
  7748. if ( geometry.uvs2.length > 0 ) {
  7749. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  7750. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  7751. }
  7752. if ( geometry.indices.length > 0 ) {
  7753. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  7754. var indices = new TypeArray( geometry.indices.length * 3 );
  7755. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  7756. }
  7757. // groups
  7758. this.groups = geometry.groups;
  7759. // morphs
  7760. for ( var name in geometry.morphTargets ) {
  7761. var array = [];
  7762. var morphTargets = geometry.morphTargets[ name ];
  7763. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  7764. var morphTarget = morphTargets[ i ];
  7765. var attribute = new Float32Attribute( morphTarget.length * 3, 3 );
  7766. array.push( attribute.copyVector3sArray( morphTarget ) );
  7767. }
  7768. this.morphAttributes[ name ] = array;
  7769. }
  7770. // skinning
  7771. if ( geometry.skinIndices.length > 0 ) {
  7772. var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 );
  7773. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  7774. }
  7775. if ( geometry.skinWeights.length > 0 ) {
  7776. var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 );
  7777. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  7778. }
  7779. //
  7780. if ( geometry.boundingSphere !== null ) {
  7781. this.boundingSphere = geometry.boundingSphere.clone();
  7782. }
  7783. if ( geometry.boundingBox !== null ) {
  7784. this.boundingBox = geometry.boundingBox.clone();
  7785. }
  7786. return this;
  7787. },
  7788. computeBoundingBox: function () {
  7789. if ( this.boundingBox === null ) {
  7790. this.boundingBox = new Box3();
  7791. }
  7792. var positions = this.attributes.position.array;
  7793. if ( positions !== undefined ) {
  7794. this.boundingBox.setFromArray( positions );
  7795. } else {
  7796. this.boundingBox.makeEmpty();
  7797. }
  7798. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  7799. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  7800. }
  7801. },
  7802. computeBoundingSphere: function () {
  7803. var box = new Box3();
  7804. var vector = new Vector3();
  7805. return function computeBoundingSphere() {
  7806. if ( this.boundingSphere === null ) {
  7807. this.boundingSphere = new Sphere();
  7808. }
  7809. var positions = this.attributes.position;
  7810. if ( positions ) {
  7811. var array = positions.array;
  7812. var center = this.boundingSphere.center;
  7813. box.setFromArray( array );
  7814. box.center( center );
  7815. // hoping to find a boundingSphere with a radius smaller than the
  7816. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7817. var maxRadiusSq = 0;
  7818. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  7819. vector.fromArray( array, i );
  7820. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  7821. }
  7822. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  7823. if ( isNaN( this.boundingSphere.radius ) ) {
  7824. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  7825. }
  7826. }
  7827. };
  7828. }(),
  7829. computeFaceNormals: function () {
  7830. // backwards compatibility
  7831. },
  7832. computeVertexNormals: function () {
  7833. var index = this.index;
  7834. var attributes = this.attributes;
  7835. var groups = this.groups;
  7836. if ( attributes.position ) {
  7837. var positions = attributes.position.array;
  7838. if ( attributes.normal === undefined ) {
  7839. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  7840. } else {
  7841. // reset existing normals to zero
  7842. var array = attributes.normal.array;
  7843. for ( var i = 0, il = array.length; i < il; i ++ ) {
  7844. array[ i ] = 0;
  7845. }
  7846. }
  7847. var normals = attributes.normal.array;
  7848. var vA, vB, vC,
  7849. pA = new Vector3(),
  7850. pB = new Vector3(),
  7851. pC = new Vector3(),
  7852. cb = new Vector3(),
  7853. ab = new Vector3();
  7854. // indexed elements
  7855. if ( index ) {
  7856. var indices = index.array;
  7857. if ( groups.length === 0 ) {
  7858. this.addGroup( 0, indices.length );
  7859. }
  7860. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  7861. var group = groups[ j ];
  7862. var start = group.start;
  7863. var count = group.count;
  7864. for ( var i = start, il = start + count; i < il; i += 3 ) {
  7865. vA = indices[ i + 0 ] * 3;
  7866. vB = indices[ i + 1 ] * 3;
  7867. vC = indices[ i + 2 ] * 3;
  7868. pA.fromArray( positions, vA );
  7869. pB.fromArray( positions, vB );
  7870. pC.fromArray( positions, vC );
  7871. cb.subVectors( pC, pB );
  7872. ab.subVectors( pA, pB );
  7873. cb.cross( ab );
  7874. normals[ vA ] += cb.x;
  7875. normals[ vA + 1 ] += cb.y;
  7876. normals[ vA + 2 ] += cb.z;
  7877. normals[ vB ] += cb.x;
  7878. normals[ vB + 1 ] += cb.y;
  7879. normals[ vB + 2 ] += cb.z;
  7880. normals[ vC ] += cb.x;
  7881. normals[ vC + 1 ] += cb.y;
  7882. normals[ vC + 2 ] += cb.z;
  7883. }
  7884. }
  7885. } else {
  7886. // non-indexed elements (unconnected triangle soup)
  7887. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  7888. pA.fromArray( positions, i );
  7889. pB.fromArray( positions, i + 3 );
  7890. pC.fromArray( positions, i + 6 );
  7891. cb.subVectors( pC, pB );
  7892. ab.subVectors( pA, pB );
  7893. cb.cross( ab );
  7894. normals[ i ] = cb.x;
  7895. normals[ i + 1 ] = cb.y;
  7896. normals[ i + 2 ] = cb.z;
  7897. normals[ i + 3 ] = cb.x;
  7898. normals[ i + 4 ] = cb.y;
  7899. normals[ i + 5 ] = cb.z;
  7900. normals[ i + 6 ] = cb.x;
  7901. normals[ i + 7 ] = cb.y;
  7902. normals[ i + 8 ] = cb.z;
  7903. }
  7904. }
  7905. this.normalizeNormals();
  7906. attributes.normal.needsUpdate = true;
  7907. }
  7908. },
  7909. merge: function ( geometry, offset ) {
  7910. if ( (geometry && geometry.isBufferGeometry) === false ) {
  7911. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7912. return;
  7913. }
  7914. if ( offset === undefined ) offset = 0;
  7915. var attributes = this.attributes;
  7916. for ( var key in attributes ) {
  7917. if ( geometry.attributes[ key ] === undefined ) continue;
  7918. var attribute1 = attributes[ key ];
  7919. var attributeArray1 = attribute1.array;
  7920. var attribute2 = geometry.attributes[ key ];
  7921. var attributeArray2 = attribute2.array;
  7922. var attributeSize = attribute2.itemSize;
  7923. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  7924. attributeArray1[ j ] = attributeArray2[ i ];
  7925. }
  7926. }
  7927. return this;
  7928. },
  7929. normalizeNormals: function () {
  7930. var normals = this.attributes.normal.array;
  7931. var x, y, z, n;
  7932. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  7933. x = normals[ i ];
  7934. y = normals[ i + 1 ];
  7935. z = normals[ i + 2 ];
  7936. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  7937. normals[ i ] *= n;
  7938. normals[ i + 1 ] *= n;
  7939. normals[ i + 2 ] *= n;
  7940. }
  7941. },
  7942. toNonIndexed: function () {
  7943. if ( this.index === null ) {
  7944. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7945. return this;
  7946. }
  7947. var geometry2 = new BufferGeometry();
  7948. var indices = this.index.array;
  7949. var attributes = this.attributes;
  7950. for ( var name in attributes ) {
  7951. var attribute = attributes[ name ];
  7952. var array = attribute.array;
  7953. var itemSize = attribute.itemSize;
  7954. var array2 = new array.constructor( indices.length * itemSize );
  7955. var index = 0, index2 = 0;
  7956. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7957. index = indices[ i ] * itemSize;
  7958. for ( var j = 0; j < itemSize; j ++ ) {
  7959. array2[ index2 ++ ] = array[ index ++ ];
  7960. }
  7961. }
  7962. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  7963. }
  7964. return geometry2;
  7965. },
  7966. toJSON: function () {
  7967. var data = {
  7968. metadata: {
  7969. version: 4.4,
  7970. type: 'BufferGeometry',
  7971. generator: 'BufferGeometry.toJSON'
  7972. }
  7973. };
  7974. // standard BufferGeometry serialization
  7975. data.uuid = this.uuid;
  7976. data.type = this.type;
  7977. if ( this.name !== '' ) data.name = this.name;
  7978. if ( this.parameters !== undefined ) {
  7979. var parameters = this.parameters;
  7980. for ( var key in parameters ) {
  7981. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7982. }
  7983. return data;
  7984. }
  7985. data.data = { attributes: {} };
  7986. var index = this.index;
  7987. if ( index !== null ) {
  7988. var array = Array.prototype.slice.call( index.array );
  7989. data.data.index = {
  7990. type: index.array.constructor.name,
  7991. array: array
  7992. };
  7993. }
  7994. var attributes = this.attributes;
  7995. for ( var key in attributes ) {
  7996. var attribute = attributes[ key ];
  7997. var array = Array.prototype.slice.call( attribute.array );
  7998. data.data.attributes[ key ] = {
  7999. itemSize: attribute.itemSize,
  8000. type: attribute.array.constructor.name,
  8001. array: array,
  8002. normalized: attribute.normalized
  8003. };
  8004. }
  8005. var groups = this.groups;
  8006. if ( groups.length > 0 ) {
  8007. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8008. }
  8009. var boundingSphere = this.boundingSphere;
  8010. if ( boundingSphere !== null ) {
  8011. data.data.boundingSphere = {
  8012. center: boundingSphere.center.toArray(),
  8013. radius: boundingSphere.radius
  8014. };
  8015. }
  8016. return data;
  8017. },
  8018. clone: function () {
  8019. /*
  8020. // Handle primitives
  8021. var parameters = this.parameters;
  8022. if ( parameters !== undefined ) {
  8023. var values = [];
  8024. for ( var key in parameters ) {
  8025. values.push( parameters[ key ] );
  8026. }
  8027. var geometry = Object.create( this.constructor.prototype );
  8028. this.constructor.apply( geometry, values );
  8029. return geometry;
  8030. }
  8031. return new this.constructor().copy( this );
  8032. */
  8033. return new BufferGeometry().copy( this );
  8034. },
  8035. copy: function ( source ) {
  8036. var index = source.index;
  8037. if ( index !== null ) {
  8038. this.setIndex( index.clone() );
  8039. }
  8040. var attributes = source.attributes;
  8041. for ( var name in attributes ) {
  8042. var attribute = attributes[ name ];
  8043. this.addAttribute( name, attribute.clone() );
  8044. }
  8045. var groups = source.groups;
  8046. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  8047. var group = groups[ i ];
  8048. this.addGroup( group.start, group.count, group.materialIndex );
  8049. }
  8050. return this;
  8051. },
  8052. dispose: function () {
  8053. this.dispatchEvent( { type: 'dispose' } );
  8054. }
  8055. } );
  8056. BufferGeometry.MaxIndex = 65535;
  8057. /**
  8058. * @author Mugen87 / https://github.com/Mugen87
  8059. */
  8060. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8061. BufferGeometry.call( this );
  8062. this.type = 'BoxBufferGeometry';
  8063. this.parameters = {
  8064. width: width,
  8065. height: height,
  8066. depth: depth,
  8067. widthSegments: widthSegments,
  8068. heightSegments: heightSegments,
  8069. depthSegments: depthSegments
  8070. };
  8071. var scope = this;
  8072. // segments
  8073. widthSegments = Math.floor( widthSegments ) || 1;
  8074. heightSegments = Math.floor( heightSegments ) || 1;
  8075. depthSegments = Math.floor( depthSegments ) || 1;
  8076. // these are used to calculate buffer length
  8077. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  8078. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  8079. // buffers
  8080. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  8081. var vertices = new Float32Array( vertexCount * 3 );
  8082. var normals = new Float32Array( vertexCount * 3 );
  8083. var uvs = new Float32Array( vertexCount * 2 );
  8084. // offset variables
  8085. var vertexBufferOffset = 0;
  8086. var uvBufferOffset = 0;
  8087. var indexBufferOffset = 0;
  8088. var numberOfVertices = 0;
  8089. // group variables
  8090. var groupStart = 0;
  8091. // build each side of the box geometry
  8092. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8093. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8094. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8095. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8096. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8097. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8098. // build geometry
  8099. this.setIndex( new BufferAttribute( indices, 1 ) );
  8100. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  8101. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  8102. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  8103. // helper functions
  8104. function calculateVertexCount( w, h, d ) {
  8105. var vertices = 0;
  8106. // calculate the amount of vertices for each side (plane)
  8107. vertices += (w + 1) * (h + 1) * 2; // xy
  8108. vertices += (w + 1) * (d + 1) * 2; // xz
  8109. vertices += (d + 1) * (h + 1) * 2; // zy
  8110. return vertices;
  8111. }
  8112. function calculateIndexCount( w, h, d ) {
  8113. var index = 0;
  8114. // calculate the amount of squares for each side
  8115. index += w * h * 2; // xy
  8116. index += w * d * 2; // xz
  8117. index += d * h * 2; // zy
  8118. return index * 6; // two triangles per square => six vertices per square
  8119. }
  8120. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8121. var segmentWidth = width / gridX;
  8122. var segmentHeight = height / gridY;
  8123. var widthHalf = width / 2;
  8124. var heightHalf = height / 2;
  8125. var depthHalf = depth / 2;
  8126. var gridX1 = gridX + 1;
  8127. var gridY1 = gridY + 1;
  8128. var vertexCounter = 0;
  8129. var groupCount = 0;
  8130. var vector = new Vector3();
  8131. // generate vertices, normals and uvs
  8132. for ( var iy = 0; iy < gridY1; iy ++ ) {
  8133. var y = iy * segmentHeight - heightHalf;
  8134. for ( var ix = 0; ix < gridX1; ix ++ ) {
  8135. var x = ix * segmentWidth - widthHalf;
  8136. // set values to correct vector component
  8137. vector[ u ] = x * udir;
  8138. vector[ v ] = y * vdir;
  8139. vector[ w ] = depthHalf;
  8140. // now apply vector to vertex buffer
  8141. vertices[ vertexBufferOffset ] = vector.x;
  8142. vertices[ vertexBufferOffset + 1 ] = vector.y;
  8143. vertices[ vertexBufferOffset + 2 ] = vector.z;
  8144. // set values to correct vector component
  8145. vector[ u ] = 0;
  8146. vector[ v ] = 0;
  8147. vector[ w ] = depth > 0 ? 1 : - 1;
  8148. // now apply vector to normal buffer
  8149. normals[ vertexBufferOffset ] = vector.x;
  8150. normals[ vertexBufferOffset + 1 ] = vector.y;
  8151. normals[ vertexBufferOffset + 2 ] = vector.z;
  8152. // uvs
  8153. uvs[ uvBufferOffset ] = ix / gridX;
  8154. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  8155. // update offsets and counters
  8156. vertexBufferOffset += 3;
  8157. uvBufferOffset += 2;
  8158. vertexCounter += 1;
  8159. }
  8160. }
  8161. // 1. you need three indices to draw a single face
  8162. // 2. a single segment consists of two faces
  8163. // 3. so we need to generate six (2*3) indices per segment
  8164. for ( iy = 0; iy < gridY; iy ++ ) {
  8165. for ( ix = 0; ix < gridX; ix ++ ) {
  8166. // indices
  8167. var a = numberOfVertices + ix + gridX1 * iy;
  8168. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8169. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8170. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8171. // face one
  8172. indices[ indexBufferOffset ] = a;
  8173. indices[ indexBufferOffset + 1 ] = b;
  8174. indices[ indexBufferOffset + 2 ] = d;
  8175. // face two
  8176. indices[ indexBufferOffset + 3 ] = b;
  8177. indices[ indexBufferOffset + 4 ] = c;
  8178. indices[ indexBufferOffset + 5 ] = d;
  8179. // update offsets and counters
  8180. indexBufferOffset += 6;
  8181. groupCount += 6;
  8182. }
  8183. }
  8184. // add a group to the geometry. this will ensure multi material support
  8185. scope.addGroup( groupStart, groupCount, materialIndex );
  8186. // calculate new start value for groups
  8187. groupStart += groupCount;
  8188. // update total number of vertices
  8189. numberOfVertices += vertexCounter;
  8190. }
  8191. }
  8192. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8193. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8194. /**
  8195. * @author bhouston / http://clara.io
  8196. */
  8197. function Ray( origin, direction ) {
  8198. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8199. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8200. }
  8201. Ray.prototype = {
  8202. constructor: Ray,
  8203. set: function ( origin, direction ) {
  8204. this.origin.copy( origin );
  8205. this.direction.copy( direction );
  8206. return this;
  8207. },
  8208. clone: function () {
  8209. return new this.constructor().copy( this );
  8210. },
  8211. copy: function ( ray ) {
  8212. this.origin.copy( ray.origin );
  8213. this.direction.copy( ray.direction );
  8214. return this;
  8215. },
  8216. at: function ( t, optionalTarget ) {
  8217. var result = optionalTarget || new Vector3();
  8218. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  8219. },
  8220. lookAt: function ( v ) {
  8221. this.direction.copy( v ).sub( this.origin ).normalize();
  8222. return this;
  8223. },
  8224. recast: function () {
  8225. var v1 = new Vector3();
  8226. return function recast( t ) {
  8227. this.origin.copy( this.at( t, v1 ) );
  8228. return this;
  8229. };
  8230. }(),
  8231. closestPointToPoint: function ( point, optionalTarget ) {
  8232. var result = optionalTarget || new Vector3();
  8233. result.subVectors( point, this.origin );
  8234. var directionDistance = result.dot( this.direction );
  8235. if ( directionDistance < 0 ) {
  8236. return result.copy( this.origin );
  8237. }
  8238. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8239. },
  8240. distanceToPoint: function ( point ) {
  8241. return Math.sqrt( this.distanceSqToPoint( point ) );
  8242. },
  8243. distanceSqToPoint: function () {
  8244. var v1 = new Vector3();
  8245. return function distanceSqToPoint( point ) {
  8246. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  8247. // point behind the ray
  8248. if ( directionDistance < 0 ) {
  8249. return this.origin.distanceToSquared( point );
  8250. }
  8251. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8252. return v1.distanceToSquared( point );
  8253. };
  8254. }(),
  8255. distanceSqToSegment: function () {
  8256. var segCenter = new Vector3();
  8257. var segDir = new Vector3();
  8258. var diff = new Vector3();
  8259. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8260. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8261. // It returns the min distance between the ray and the segment
  8262. // defined by v0 and v1
  8263. // It can also set two optional targets :
  8264. // - The closest point on the ray
  8265. // - The closest point on the segment
  8266. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8267. segDir.copy( v1 ).sub( v0 ).normalize();
  8268. diff.copy( this.origin ).sub( segCenter );
  8269. var segExtent = v0.distanceTo( v1 ) * 0.5;
  8270. var a01 = - this.direction.dot( segDir );
  8271. var b0 = diff.dot( this.direction );
  8272. var b1 = - diff.dot( segDir );
  8273. var c = diff.lengthSq();
  8274. var det = Math.abs( 1 - a01 * a01 );
  8275. var s0, s1, sqrDist, extDet;
  8276. if ( det > 0 ) {
  8277. // The ray and segment are not parallel.
  8278. s0 = a01 * b1 - b0;
  8279. s1 = a01 * b0 - b1;
  8280. extDet = segExtent * det;
  8281. if ( s0 >= 0 ) {
  8282. if ( s1 >= - extDet ) {
  8283. if ( s1 <= extDet ) {
  8284. // region 0
  8285. // Minimum at interior points of ray and segment.
  8286. var invDet = 1 / det;
  8287. s0 *= invDet;
  8288. s1 *= invDet;
  8289. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8290. } else {
  8291. // region 1
  8292. s1 = segExtent;
  8293. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8294. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8295. }
  8296. } else {
  8297. // region 5
  8298. s1 = - segExtent;
  8299. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8300. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8301. }
  8302. } else {
  8303. if ( s1 <= - extDet ) {
  8304. // region 4
  8305. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8306. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8307. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8308. } else if ( s1 <= extDet ) {
  8309. // region 3
  8310. s0 = 0;
  8311. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8312. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8313. } else {
  8314. // region 2
  8315. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8316. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8317. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8318. }
  8319. }
  8320. } else {
  8321. // Ray and segment are parallel.
  8322. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8323. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8324. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8325. }
  8326. if ( optionalPointOnRay ) {
  8327. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  8328. }
  8329. if ( optionalPointOnSegment ) {
  8330. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  8331. }
  8332. return sqrDist;
  8333. };
  8334. }(),
  8335. intersectSphere: function () {
  8336. var v1 = new Vector3();
  8337. return function intersectSphere( sphere, optionalTarget ) {
  8338. v1.subVectors( sphere.center, this.origin );
  8339. var tca = v1.dot( this.direction );
  8340. var d2 = v1.dot( v1 ) - tca * tca;
  8341. var radius2 = sphere.radius * sphere.radius;
  8342. if ( d2 > radius2 ) return null;
  8343. var thc = Math.sqrt( radius2 - d2 );
  8344. // t0 = first intersect point - entrance on front of sphere
  8345. var t0 = tca - thc;
  8346. // t1 = second intersect point - exit point on back of sphere
  8347. var t1 = tca + thc;
  8348. // test to see if both t0 and t1 are behind the ray - if so, return null
  8349. if ( t0 < 0 && t1 < 0 ) return null;
  8350. // test to see if t0 is behind the ray:
  8351. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8352. // in order to always return an intersect point that is in front of the ray.
  8353. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  8354. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8355. return this.at( t0, optionalTarget );
  8356. };
  8357. }(),
  8358. intersectsSphere: function ( sphere ) {
  8359. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  8360. },
  8361. distanceToPlane: function ( plane ) {
  8362. var denominator = plane.normal.dot( this.direction );
  8363. if ( denominator === 0 ) {
  8364. // line is coplanar, return origin
  8365. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8366. return 0;
  8367. }
  8368. // Null is preferable to undefined since undefined means.... it is undefined
  8369. return null;
  8370. }
  8371. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8372. // Return if the ray never intersects the plane
  8373. return t >= 0 ? t : null;
  8374. },
  8375. intersectPlane: function ( plane, optionalTarget ) {
  8376. var t = this.distanceToPlane( plane );
  8377. if ( t === null ) {
  8378. return null;
  8379. }
  8380. return this.at( t, optionalTarget );
  8381. },
  8382. intersectsPlane: function ( plane ) {
  8383. // check if the ray lies on the plane first
  8384. var distToPoint = plane.distanceToPoint( this.origin );
  8385. if ( distToPoint === 0 ) {
  8386. return true;
  8387. }
  8388. var denominator = plane.normal.dot( this.direction );
  8389. if ( denominator * distToPoint < 0 ) {
  8390. return true;
  8391. }
  8392. // ray origin is behind the plane (and is pointing behind it)
  8393. return false;
  8394. },
  8395. intersectBox: function ( box, optionalTarget ) {
  8396. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  8397. var invdirx = 1 / this.direction.x,
  8398. invdiry = 1 / this.direction.y,
  8399. invdirz = 1 / this.direction.z;
  8400. var origin = this.origin;
  8401. if ( invdirx >= 0 ) {
  8402. tmin = ( box.min.x - origin.x ) * invdirx;
  8403. tmax = ( box.max.x - origin.x ) * invdirx;
  8404. } else {
  8405. tmin = ( box.max.x - origin.x ) * invdirx;
  8406. tmax = ( box.min.x - origin.x ) * invdirx;
  8407. }
  8408. if ( invdiry >= 0 ) {
  8409. tymin = ( box.min.y - origin.y ) * invdiry;
  8410. tymax = ( box.max.y - origin.y ) * invdiry;
  8411. } else {
  8412. tymin = ( box.max.y - origin.y ) * invdiry;
  8413. tymax = ( box.min.y - origin.y ) * invdiry;
  8414. }
  8415. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8416. // These lines also handle the case where tmin or tmax is NaN
  8417. // (result of 0 * Infinity). x !== x returns true if x is NaN
  8418. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  8419. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  8420. if ( invdirz >= 0 ) {
  8421. tzmin = ( box.min.z - origin.z ) * invdirz;
  8422. tzmax = ( box.max.z - origin.z ) * invdirz;
  8423. } else {
  8424. tzmin = ( box.max.z - origin.z ) * invdirz;
  8425. tzmax = ( box.min.z - origin.z ) * invdirz;
  8426. }
  8427. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8428. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8429. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8430. //return point closest to the ray (positive side)
  8431. if ( tmax < 0 ) return null;
  8432. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  8433. },
  8434. intersectsBox: ( function () {
  8435. var v = new Vector3();
  8436. return function intersectsBox( box ) {
  8437. return this.intersectBox( box, v ) !== null;
  8438. };
  8439. } )(),
  8440. intersectTriangle: function () {
  8441. // Compute the offset origin, edges, and normal.
  8442. var diff = new Vector3();
  8443. var edge1 = new Vector3();
  8444. var edge2 = new Vector3();
  8445. var normal = new Vector3();
  8446. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  8447. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8448. edge1.subVectors( b, a );
  8449. edge2.subVectors( c, a );
  8450. normal.crossVectors( edge1, edge2 );
  8451. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8452. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8453. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8454. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8455. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8456. var DdN = this.direction.dot( normal );
  8457. var sign;
  8458. if ( DdN > 0 ) {
  8459. if ( backfaceCulling ) return null;
  8460. sign = 1;
  8461. } else if ( DdN < 0 ) {
  8462. sign = - 1;
  8463. DdN = - DdN;
  8464. } else {
  8465. return null;
  8466. }
  8467. diff.subVectors( this.origin, a );
  8468. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  8469. // b1 < 0, no intersection
  8470. if ( DdQxE2 < 0 ) {
  8471. return null;
  8472. }
  8473. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  8474. // b2 < 0, no intersection
  8475. if ( DdE1xQ < 0 ) {
  8476. return null;
  8477. }
  8478. // b1+b2 > 1, no intersection
  8479. if ( DdQxE2 + DdE1xQ > DdN ) {
  8480. return null;
  8481. }
  8482. // Line intersects triangle, check if ray does.
  8483. var QdN = - sign * diff.dot( normal );
  8484. // t < 0, no intersection
  8485. if ( QdN < 0 ) {
  8486. return null;
  8487. }
  8488. // Ray intersects triangle.
  8489. return this.at( QdN / DdN, optionalTarget );
  8490. };
  8491. }(),
  8492. applyMatrix4: function ( matrix4 ) {
  8493. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  8494. this.origin.applyMatrix4( matrix4 );
  8495. this.direction.sub( this.origin );
  8496. this.direction.normalize();
  8497. return this;
  8498. },
  8499. equals: function ( ray ) {
  8500. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8501. }
  8502. };
  8503. /**
  8504. * @author bhouston / http://clara.io
  8505. */
  8506. function Line3( start, end ) {
  8507. this.start = ( start !== undefined ) ? start : new Vector3();
  8508. this.end = ( end !== undefined ) ? end : new Vector3();
  8509. }
  8510. Line3.prototype = {
  8511. constructor: Line3,
  8512. set: function ( start, end ) {
  8513. this.start.copy( start );
  8514. this.end.copy( end );
  8515. return this;
  8516. },
  8517. clone: function () {
  8518. return new this.constructor().copy( this );
  8519. },
  8520. copy: function ( line ) {
  8521. this.start.copy( line.start );
  8522. this.end.copy( line.end );
  8523. return this;
  8524. },
  8525. center: function ( optionalTarget ) {
  8526. var result = optionalTarget || new Vector3();
  8527. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  8528. },
  8529. delta: function ( optionalTarget ) {
  8530. var result = optionalTarget || new Vector3();
  8531. return result.subVectors( this.end, this.start );
  8532. },
  8533. distanceSq: function () {
  8534. return this.start.distanceToSquared( this.end );
  8535. },
  8536. distance: function () {
  8537. return this.start.distanceTo( this.end );
  8538. },
  8539. at: function ( t, optionalTarget ) {
  8540. var result = optionalTarget || new Vector3();
  8541. return this.delta( result ).multiplyScalar( t ).add( this.start );
  8542. },
  8543. closestPointToPointParameter: function () {
  8544. var startP = new Vector3();
  8545. var startEnd = new Vector3();
  8546. return function closestPointToPointParameter( point, clampToLine ) {
  8547. startP.subVectors( point, this.start );
  8548. startEnd.subVectors( this.end, this.start );
  8549. var startEnd2 = startEnd.dot( startEnd );
  8550. var startEnd_startP = startEnd.dot( startP );
  8551. var t = startEnd_startP / startEnd2;
  8552. if ( clampToLine ) {
  8553. t = exports.Math.clamp( t, 0, 1 );
  8554. }
  8555. return t;
  8556. };
  8557. }(),
  8558. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  8559. var t = this.closestPointToPointParameter( point, clampToLine );
  8560. var result = optionalTarget || new Vector3();
  8561. return this.delta( result ).multiplyScalar( t ).add( this.start );
  8562. },
  8563. applyMatrix4: function ( matrix ) {
  8564. this.start.applyMatrix4( matrix );
  8565. this.end.applyMatrix4( matrix );
  8566. return this;
  8567. },
  8568. equals: function ( line ) {
  8569. return line.start.equals( this.start ) && line.end.equals( this.end );
  8570. }
  8571. };
  8572. /**
  8573. * @author bhouston / http://clara.io
  8574. * @author mrdoob / http://mrdoob.com/
  8575. */
  8576. function Triangle( a, b, c ) {
  8577. this.a = ( a !== undefined ) ? a : new Vector3();
  8578. this.b = ( b !== undefined ) ? b : new Vector3();
  8579. this.c = ( c !== undefined ) ? c : new Vector3();
  8580. }
  8581. Triangle.normal = function () {
  8582. var v0 = new Vector3();
  8583. return function normal( a, b, c, optionalTarget ) {
  8584. var result = optionalTarget || new Vector3();
  8585. result.subVectors( c, b );
  8586. v0.subVectors( a, b );
  8587. result.cross( v0 );
  8588. var resultLengthSq = result.lengthSq();
  8589. if ( resultLengthSq > 0 ) {
  8590. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  8591. }
  8592. return result.set( 0, 0, 0 );
  8593. };
  8594. }();
  8595. // static/instance method to calculate barycentric coordinates
  8596. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  8597. Triangle.barycoordFromPoint = function () {
  8598. var v0 = new Vector3();
  8599. var v1 = new Vector3();
  8600. var v2 = new Vector3();
  8601. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  8602. v0.subVectors( c, a );
  8603. v1.subVectors( b, a );
  8604. v2.subVectors( point, a );
  8605. var dot00 = v0.dot( v0 );
  8606. var dot01 = v0.dot( v1 );
  8607. var dot02 = v0.dot( v2 );
  8608. var dot11 = v1.dot( v1 );
  8609. var dot12 = v1.dot( v2 );
  8610. var denom = ( dot00 * dot11 - dot01 * dot01 );
  8611. var result = optionalTarget || new Vector3();
  8612. // collinear or singular triangle
  8613. if ( denom === 0 ) {
  8614. // arbitrary location outside of triangle?
  8615. // not sure if this is the best idea, maybe should be returning undefined
  8616. return result.set( - 2, - 1, - 1 );
  8617. }
  8618. var invDenom = 1 / denom;
  8619. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  8620. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  8621. // barycentric coordinates must always sum to 1
  8622. return result.set( 1 - u - v, v, u );
  8623. };
  8624. }();
  8625. Triangle.containsPoint = function () {
  8626. var v1 = new Vector3();
  8627. return function containsPoint( point, a, b, c ) {
  8628. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  8629. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  8630. };
  8631. }();
  8632. Triangle.prototype = {
  8633. constructor: Triangle,
  8634. set: function ( a, b, c ) {
  8635. this.a.copy( a );
  8636. this.b.copy( b );
  8637. this.c.copy( c );
  8638. return this;
  8639. },
  8640. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  8641. this.a.copy( points[ i0 ] );
  8642. this.b.copy( points[ i1 ] );
  8643. this.c.copy( points[ i2 ] );
  8644. return this;
  8645. },
  8646. clone: function () {
  8647. return new this.constructor().copy( this );
  8648. },
  8649. copy: function ( triangle ) {
  8650. this.a.copy( triangle.a );
  8651. this.b.copy( triangle.b );
  8652. this.c.copy( triangle.c );
  8653. return this;
  8654. },
  8655. area: function () {
  8656. var v0 = new Vector3();
  8657. var v1 = new Vector3();
  8658. return function area() {
  8659. v0.subVectors( this.c, this.b );
  8660. v1.subVectors( this.a, this.b );
  8661. return v0.cross( v1 ).length() * 0.5;
  8662. };
  8663. }(),
  8664. midpoint: function ( optionalTarget ) {
  8665. var result = optionalTarget || new Vector3();
  8666. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  8667. },
  8668. normal: function ( optionalTarget ) {
  8669. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  8670. },
  8671. plane: function ( optionalTarget ) {
  8672. var result = optionalTarget || new Plane();
  8673. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  8674. },
  8675. barycoordFromPoint: function ( point, optionalTarget ) {
  8676. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  8677. },
  8678. containsPoint: function ( point ) {
  8679. return Triangle.containsPoint( point, this.a, this.b, this.c );
  8680. },
  8681. closestPointToPoint: function () {
  8682. var plane, edgeList, projectedPoint, closestPoint;
  8683. return function closestPointToPoint( point, optionalTarget ) {
  8684. if ( plane === undefined ) {
  8685. plane = new Plane();
  8686. edgeList = [ new Line3(), new Line3(), new Line3() ];
  8687. projectedPoint = new Vector3();
  8688. closestPoint = new Vector3();
  8689. }
  8690. var result = optionalTarget || new Vector3();
  8691. var minDistance = Infinity;
  8692. // project the point onto the plane of the triangle
  8693. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  8694. plane.projectPoint( point, projectedPoint );
  8695. // check if the projection lies within the triangle
  8696. if( this.containsPoint( projectedPoint ) === true ) {
  8697. // if so, this is the closest point
  8698. result.copy( projectedPoint );
  8699. } else {
  8700. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  8701. edgeList[ 0 ].set( this.a, this.b );
  8702. edgeList[ 1 ].set( this.b, this.c );
  8703. edgeList[ 2 ].set( this.c, this.a );
  8704. for( var i = 0; i < edgeList.length; i ++ ) {
  8705. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  8706. var distance = projectedPoint.distanceToSquared( closestPoint );
  8707. if( distance < minDistance ) {
  8708. minDistance = distance;
  8709. result.copy( closestPoint );
  8710. }
  8711. }
  8712. }
  8713. return result;
  8714. };
  8715. }(),
  8716. equals: function ( triangle ) {
  8717. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  8718. }
  8719. };
  8720. /**
  8721. * @author mrdoob / http://mrdoob.com/
  8722. * @author alteredq / http://alteredqualia.com/
  8723. *
  8724. * parameters = {
  8725. * color: <hex>,
  8726. * opacity: <float>,
  8727. * map: new THREE.Texture( <Image> ),
  8728. *
  8729. * aoMap: new THREE.Texture( <Image> ),
  8730. * aoMapIntensity: <float>
  8731. *
  8732. * specularMap: new THREE.Texture( <Image> ),
  8733. *
  8734. * alphaMap: new THREE.Texture( <Image> ),
  8735. *
  8736. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8737. * combine: THREE.Multiply,
  8738. * reflectivity: <float>,
  8739. * refractionRatio: <float>,
  8740. *
  8741. * shading: THREE.SmoothShading,
  8742. * depthTest: <bool>,
  8743. * depthWrite: <bool>,
  8744. *
  8745. * wireframe: <boolean>,
  8746. * wireframeLinewidth: <float>,
  8747. *
  8748. * skinning: <bool>,
  8749. * morphTargets: <bool>
  8750. * }
  8751. */
  8752. function MeshBasicMaterial( parameters ) {
  8753. Material.call( this );
  8754. this.type = 'MeshBasicMaterial';
  8755. this.color = new Color( 0xffffff ); // emissive
  8756. this.map = null;
  8757. this.aoMap = null;
  8758. this.aoMapIntensity = 1.0;
  8759. this.specularMap = null;
  8760. this.alphaMap = null;
  8761. this.envMap = null;
  8762. this.combine = MultiplyOperation;
  8763. this.reflectivity = 1;
  8764. this.refractionRatio = 0.98;
  8765. this.wireframe = false;
  8766. this.wireframeLinewidth = 1;
  8767. this.wireframeLinecap = 'round';
  8768. this.wireframeLinejoin = 'round';
  8769. this.skinning = false;
  8770. this.morphTargets = false;
  8771. this.lights = false;
  8772. this.setValues( parameters );
  8773. }
  8774. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8775. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8776. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8777. MeshBasicMaterial.prototype.copy = function ( source ) {
  8778. Material.prototype.copy.call( this, source );
  8779. this.color.copy( source.color );
  8780. this.map = source.map;
  8781. this.aoMap = source.aoMap;
  8782. this.aoMapIntensity = source.aoMapIntensity;
  8783. this.specularMap = source.specularMap;
  8784. this.alphaMap = source.alphaMap;
  8785. this.envMap = source.envMap;
  8786. this.combine = source.combine;
  8787. this.reflectivity = source.reflectivity;
  8788. this.refractionRatio = source.refractionRatio;
  8789. this.wireframe = source.wireframe;
  8790. this.wireframeLinewidth = source.wireframeLinewidth;
  8791. this.wireframeLinecap = source.wireframeLinecap;
  8792. this.wireframeLinejoin = source.wireframeLinejoin;
  8793. this.skinning = source.skinning;
  8794. this.morphTargets = source.morphTargets;
  8795. return this;
  8796. };
  8797. /**
  8798. * @author mrdoob / http://mrdoob.com/
  8799. * @author alteredq / http://alteredqualia.com/
  8800. * @author mikael emtinger / http://gomo.se/
  8801. * @author jonobr1 / http://jonobr1.com/
  8802. */
  8803. function Mesh( geometry, material ) {
  8804. Object3D.call( this );
  8805. this.type = 'Mesh';
  8806. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8807. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8808. this.drawMode = TrianglesDrawMode;
  8809. this.updateMorphTargets();
  8810. }
  8811. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8812. constructor: Mesh,
  8813. isMesh: true,
  8814. setDrawMode: function ( value ) {
  8815. this.drawMode = value;
  8816. },
  8817. copy: function ( source ) {
  8818. Object3D.prototype.copy.call( this, source );
  8819. this.drawMode = source.drawMode;
  8820. return this;
  8821. },
  8822. updateMorphTargets: function () {
  8823. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8824. this.morphTargetBase = - 1;
  8825. this.morphTargetInfluences = [];
  8826. this.morphTargetDictionary = {};
  8827. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8828. this.morphTargetInfluences.push( 0 );
  8829. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8830. }
  8831. }
  8832. },
  8833. getMorphTargetIndexByName: function ( name ) {
  8834. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8835. return this.morphTargetDictionary[ name ];
  8836. }
  8837. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  8838. return 0;
  8839. },
  8840. raycast: ( function () {
  8841. var inverseMatrix = new Matrix4();
  8842. var ray = new Ray();
  8843. var sphere = new Sphere();
  8844. var vA = new Vector3();
  8845. var vB = new Vector3();
  8846. var vC = new Vector3();
  8847. var tempA = new Vector3();
  8848. var tempB = new Vector3();
  8849. var tempC = new Vector3();
  8850. var uvA = new Vector2();
  8851. var uvB = new Vector2();
  8852. var uvC = new Vector2();
  8853. var barycoord = new Vector3();
  8854. var intersectionPoint = new Vector3();
  8855. var intersectionPointWorld = new Vector3();
  8856. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8857. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8858. uv1.multiplyScalar( barycoord.x );
  8859. uv2.multiplyScalar( barycoord.y );
  8860. uv3.multiplyScalar( barycoord.z );
  8861. uv1.add( uv2 ).add( uv3 );
  8862. return uv1.clone();
  8863. }
  8864. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8865. var intersect;
  8866. var material = object.material;
  8867. if ( material.side === BackSide ) {
  8868. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8869. } else {
  8870. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8871. }
  8872. if ( intersect === null ) return null;
  8873. intersectionPointWorld.copy( point );
  8874. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8875. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8876. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8877. return {
  8878. distance: distance,
  8879. point: intersectionPointWorld.clone(),
  8880. object: object
  8881. };
  8882. }
  8883. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  8884. vA.fromArray( positions, a * 3 );
  8885. vB.fromArray( positions, b * 3 );
  8886. vC.fromArray( positions, c * 3 );
  8887. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8888. if ( intersection ) {
  8889. if ( uvs ) {
  8890. uvA.fromArray( uvs, a * 2 );
  8891. uvB.fromArray( uvs, b * 2 );
  8892. uvC.fromArray( uvs, c * 2 );
  8893. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8894. }
  8895. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8896. intersection.faceIndex = a;
  8897. }
  8898. return intersection;
  8899. }
  8900. return function raycast( raycaster, intersects ) {
  8901. var geometry = this.geometry;
  8902. var material = this.material;
  8903. var matrixWorld = this.matrixWorld;
  8904. if ( material === undefined ) return;
  8905. // Checking boundingSphere distance to ray
  8906. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8907. sphere.copy( geometry.boundingSphere );
  8908. sphere.applyMatrix4( matrixWorld );
  8909. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8910. //
  8911. inverseMatrix.getInverse( matrixWorld );
  8912. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8913. // Check boundingBox before continuing
  8914. if ( geometry.boundingBox !== null ) {
  8915. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8916. }
  8917. var uvs, intersection;
  8918. if ( (geometry && geometry.isBufferGeometry) ) {
  8919. var a, b, c;
  8920. var index = geometry.index;
  8921. var attributes = geometry.attributes;
  8922. var positions = attributes.position.array;
  8923. if ( attributes.uv !== undefined ) {
  8924. uvs = attributes.uv.array;
  8925. }
  8926. if ( index !== null ) {
  8927. var indices = index.array;
  8928. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  8929. a = indices[ i ];
  8930. b = indices[ i + 1 ];
  8931. c = indices[ i + 2 ];
  8932. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8933. if ( intersection ) {
  8934. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8935. intersects.push( intersection );
  8936. }
  8937. }
  8938. } else {
  8939. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  8940. a = i / 3;
  8941. b = a + 1;
  8942. c = a + 2;
  8943. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8944. if ( intersection ) {
  8945. intersection.index = a; // triangle number in positions buffer semantics
  8946. intersects.push( intersection );
  8947. }
  8948. }
  8949. }
  8950. } else if ( (geometry && geometry.isGeometry) ) {
  8951. var fvA, fvB, fvC;
  8952. var isFaceMaterial = (material && material.isMultiMaterial);
  8953. var materials = isFaceMaterial === true ? material.materials : null;
  8954. var vertices = geometry.vertices;
  8955. var faces = geometry.faces;
  8956. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8957. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8958. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  8959. var face = faces[ f ];
  8960. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  8961. if ( faceMaterial === undefined ) continue;
  8962. fvA = vertices[ face.a ];
  8963. fvB = vertices[ face.b ];
  8964. fvC = vertices[ face.c ];
  8965. if ( faceMaterial.morphTargets === true ) {
  8966. var morphTargets = geometry.morphTargets;
  8967. var morphInfluences = this.morphTargetInfluences;
  8968. vA.set( 0, 0, 0 );
  8969. vB.set( 0, 0, 0 );
  8970. vC.set( 0, 0, 0 );
  8971. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8972. var influence = morphInfluences[ t ];
  8973. if ( influence === 0 ) continue;
  8974. var targets = morphTargets[ t ].vertices;
  8975. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  8976. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  8977. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  8978. }
  8979. vA.add( fvA );
  8980. vB.add( fvB );
  8981. vC.add( fvC );
  8982. fvA = vA;
  8983. fvB = vB;
  8984. fvC = vC;
  8985. }
  8986. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  8987. if ( intersection ) {
  8988. if ( uvs ) {
  8989. var uvs_f = uvs[ f ];
  8990. uvA.copy( uvs_f[ 0 ] );
  8991. uvB.copy( uvs_f[ 1 ] );
  8992. uvC.copy( uvs_f[ 2 ] );
  8993. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  8994. }
  8995. intersection.face = face;
  8996. intersection.faceIndex = f;
  8997. intersects.push( intersection );
  8998. }
  8999. }
  9000. }
  9001. };
  9002. }() ),
  9003. clone: function () {
  9004. return new this.constructor( this.geometry, this.material ).copy( this );
  9005. }
  9006. } );
  9007. /**
  9008. * @author mrdoob / http://mrdoob.com/
  9009. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9010. */
  9011. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9012. BufferGeometry.call( this );
  9013. this.type = 'PlaneBufferGeometry';
  9014. this.parameters = {
  9015. width: width,
  9016. height: height,
  9017. widthSegments: widthSegments,
  9018. heightSegments: heightSegments
  9019. };
  9020. var width_half = width / 2;
  9021. var height_half = height / 2;
  9022. var gridX = Math.floor( widthSegments ) || 1;
  9023. var gridY = Math.floor( heightSegments ) || 1;
  9024. var gridX1 = gridX + 1;
  9025. var gridY1 = gridY + 1;
  9026. var segment_width = width / gridX;
  9027. var segment_height = height / gridY;
  9028. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9029. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9030. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9031. var offset = 0;
  9032. var offset2 = 0;
  9033. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9034. var y = iy * segment_height - height_half;
  9035. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9036. var x = ix * segment_width - width_half;
  9037. vertices[ offset ] = x;
  9038. vertices[ offset + 1 ] = - y;
  9039. normals[ offset + 2 ] = 1;
  9040. uvs[ offset2 ] = ix / gridX;
  9041. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9042. offset += 3;
  9043. offset2 += 2;
  9044. }
  9045. }
  9046. offset = 0;
  9047. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9048. for ( var iy = 0; iy < gridY; iy ++ ) {
  9049. for ( var ix = 0; ix < gridX; ix ++ ) {
  9050. var a = ix + gridX1 * iy;
  9051. var b = ix + gridX1 * ( iy + 1 );
  9052. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9053. var d = ( ix + 1 ) + gridX1 * iy;
  9054. indices[ offset ] = a;
  9055. indices[ offset + 1 ] = b;
  9056. indices[ offset + 2 ] = d;
  9057. indices[ offset + 3 ] = b;
  9058. indices[ offset + 4 ] = c;
  9059. indices[ offset + 5 ] = d;
  9060. offset += 6;
  9061. }
  9062. }
  9063. this.setIndex( new BufferAttribute( indices, 1 ) );
  9064. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9065. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9066. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9067. }
  9068. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9069. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9070. /**
  9071. * @author mrdoob / http://mrdoob.com/
  9072. * @author mikael emtinger / http://gomo.se/
  9073. * @author WestLangley / http://github.com/WestLangley
  9074. */
  9075. function Camera() {
  9076. Object3D.call( this );
  9077. this.type = 'Camera';
  9078. this.matrixWorldInverse = new Matrix4();
  9079. this.projectionMatrix = new Matrix4();
  9080. }
  9081. Camera.prototype = Object.create( Object3D.prototype );
  9082. Camera.prototype.constructor = Camera;
  9083. Camera.prototype.isCamera = true;
  9084. Camera.prototype.getWorldDirection = function () {
  9085. var quaternion = new Quaternion();
  9086. return function getWorldDirection( optionalTarget ) {
  9087. var result = optionalTarget || new Vector3();
  9088. this.getWorldQuaternion( quaternion );
  9089. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9090. };
  9091. }();
  9092. Camera.prototype.lookAt = function () {
  9093. // This routine does not support cameras with rotated and/or translated parent(s)
  9094. var m1 = new Matrix4();
  9095. return function lookAt( vector ) {
  9096. m1.lookAt( this.position, vector, this.up );
  9097. this.quaternion.setFromRotationMatrix( m1 );
  9098. };
  9099. }();
  9100. Camera.prototype.clone = function () {
  9101. return new this.constructor().copy( this );
  9102. };
  9103. Camera.prototype.copy = function ( source ) {
  9104. Object3D.prototype.copy.call( this, source );
  9105. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9106. this.projectionMatrix.copy( source.projectionMatrix );
  9107. return this;
  9108. };
  9109. /**
  9110. * @author mrdoob / http://mrdoob.com/
  9111. * @author greggman / http://games.greggman.com/
  9112. * @author zz85 / http://www.lab4games.net/zz85/blog
  9113. * @author tschw
  9114. */
  9115. function PerspectiveCamera( fov, aspect, near, far ) {
  9116. Camera.call( this );
  9117. this.type = 'PerspectiveCamera';
  9118. this.fov = fov !== undefined ? fov : 50;
  9119. this.zoom = 1;
  9120. this.near = near !== undefined ? near : 0.1;
  9121. this.far = far !== undefined ? far : 2000;
  9122. this.focus = 10;
  9123. this.aspect = aspect !== undefined ? aspect : 1;
  9124. this.view = null;
  9125. this.filmGauge = 35; // width of the film (default in millimeters)
  9126. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9127. this.updateProjectionMatrix();
  9128. }
  9129. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9130. constructor: PerspectiveCamera,
  9131. isPerspectiveCamera: true,
  9132. copy: function ( source ) {
  9133. Camera.prototype.copy.call( this, source );
  9134. this.fov = source.fov;
  9135. this.zoom = source.zoom;
  9136. this.near = source.near;
  9137. this.far = source.far;
  9138. this.focus = source.focus;
  9139. this.aspect = source.aspect;
  9140. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9141. this.filmGauge = source.filmGauge;
  9142. this.filmOffset = source.filmOffset;
  9143. return this;
  9144. },
  9145. /**
  9146. * Sets the FOV by focal length in respect to the current .filmGauge.
  9147. *
  9148. * The default film gauge is 35, so that the focal length can be specified for
  9149. * a 35mm (full frame) camera.
  9150. *
  9151. * Values for focal length and film gauge must have the same unit.
  9152. */
  9153. setFocalLength: function ( focalLength ) {
  9154. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9155. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9156. this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9157. this.updateProjectionMatrix();
  9158. },
  9159. /**
  9160. * Calculates the focal length from the current .fov and .filmGauge.
  9161. */
  9162. getFocalLength: function () {
  9163. var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov );
  9164. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9165. },
  9166. getEffectiveFOV: function () {
  9167. return exports.Math.RAD2DEG * 2 * Math.atan(
  9168. Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9169. },
  9170. getFilmWidth: function () {
  9171. // film not completely covered in portrait format (aspect < 1)
  9172. return this.filmGauge * Math.min( this.aspect, 1 );
  9173. },
  9174. getFilmHeight: function () {
  9175. // film not completely covered in landscape format (aspect > 1)
  9176. return this.filmGauge / Math.max( this.aspect, 1 );
  9177. },
  9178. /**
  9179. * Sets an offset in a larger frustum. This is useful for multi-window or
  9180. * multi-monitor/multi-machine setups.
  9181. *
  9182. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9183. * the monitors are in grid like this
  9184. *
  9185. * +---+---+---+
  9186. * | A | B | C |
  9187. * +---+---+---+
  9188. * | D | E | F |
  9189. * +---+---+---+
  9190. *
  9191. * then for each monitor you would call it like this
  9192. *
  9193. * var w = 1920;
  9194. * var h = 1080;
  9195. * var fullWidth = w * 3;
  9196. * var fullHeight = h * 2;
  9197. *
  9198. * --A--
  9199. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9200. * --B--
  9201. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9202. * --C--
  9203. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9204. * --D--
  9205. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9206. * --E--
  9207. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9208. * --F--
  9209. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9210. *
  9211. * Note there is no reason monitors have to be the same size or in a grid.
  9212. */
  9213. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9214. this.aspect = fullWidth / fullHeight;
  9215. this.view = {
  9216. fullWidth: fullWidth,
  9217. fullHeight: fullHeight,
  9218. offsetX: x,
  9219. offsetY: y,
  9220. width: width,
  9221. height: height
  9222. };
  9223. this.updateProjectionMatrix();
  9224. },
  9225. clearViewOffset: function() {
  9226. this.view = null;
  9227. this.updateProjectionMatrix();
  9228. },
  9229. updateProjectionMatrix: function () {
  9230. var near = this.near,
  9231. top = near * Math.tan(
  9232. exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9233. height = 2 * top,
  9234. width = this.aspect * height,
  9235. left = - 0.5 * width,
  9236. view = this.view;
  9237. if ( view !== null ) {
  9238. var fullWidth = view.fullWidth,
  9239. fullHeight = view.fullHeight;
  9240. left += view.offsetX * width / fullWidth;
  9241. top -= view.offsetY * height / fullHeight;
  9242. width *= view.width / fullWidth;
  9243. height *= view.height / fullHeight;
  9244. }
  9245. var skew = this.filmOffset;
  9246. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9247. this.projectionMatrix.makeFrustum(
  9248. left, left + width, top - height, top, near, this.far );
  9249. },
  9250. toJSON: function ( meta ) {
  9251. var data = Object3D.prototype.toJSON.call( this, meta );
  9252. data.object.fov = this.fov;
  9253. data.object.zoom = this.zoom;
  9254. data.object.near = this.near;
  9255. data.object.far = this.far;
  9256. data.object.focus = this.focus;
  9257. data.object.aspect = this.aspect;
  9258. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9259. data.object.filmGauge = this.filmGauge;
  9260. data.object.filmOffset = this.filmOffset;
  9261. return data;
  9262. }
  9263. } );
  9264. /**
  9265. * @author alteredq / http://alteredqualia.com/
  9266. * @author arose / http://github.com/arose
  9267. */
  9268. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9269. Camera.call( this );
  9270. this.type = 'OrthographicCamera';
  9271. this.zoom = 1;
  9272. this.view = null;
  9273. this.left = left;
  9274. this.right = right;
  9275. this.top = top;
  9276. this.bottom = bottom;
  9277. this.near = ( near !== undefined ) ? near : 0.1;
  9278. this.far = ( far !== undefined ) ? far : 2000;
  9279. this.updateProjectionMatrix();
  9280. }
  9281. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9282. constructor: OrthographicCamera,
  9283. isOrthographicCamera: true,
  9284. copy: function ( source ) {
  9285. Camera.prototype.copy.call( this, source );
  9286. this.left = source.left;
  9287. this.right = source.right;
  9288. this.top = source.top;
  9289. this.bottom = source.bottom;
  9290. this.near = source.near;
  9291. this.far = source.far;
  9292. this.zoom = source.zoom;
  9293. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9294. return this;
  9295. },
  9296. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9297. this.view = {
  9298. fullWidth: fullWidth,
  9299. fullHeight: fullHeight,
  9300. offsetX: x,
  9301. offsetY: y,
  9302. width: width,
  9303. height: height
  9304. };
  9305. this.updateProjectionMatrix();
  9306. },
  9307. clearViewOffset: function() {
  9308. this.view = null;
  9309. this.updateProjectionMatrix();
  9310. },
  9311. updateProjectionMatrix: function () {
  9312. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9313. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9314. var cx = ( this.right + this.left ) / 2;
  9315. var cy = ( this.top + this.bottom ) / 2;
  9316. var left = cx - dx;
  9317. var right = cx + dx;
  9318. var top = cy + dy;
  9319. var bottom = cy - dy;
  9320. if ( this.view !== null ) {
  9321. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9322. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9323. var scaleW = ( this.right - this.left ) / this.view.width;
  9324. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9325. left += scaleW * ( this.view.offsetX / zoomW );
  9326. right = left + scaleW * ( this.view.width / zoomW );
  9327. top -= scaleH * ( this.view.offsetY / zoomH );
  9328. bottom = top - scaleH * ( this.view.height / zoomH );
  9329. }
  9330. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9331. },
  9332. toJSON: function ( meta ) {
  9333. var data = Object3D.prototype.toJSON.call( this, meta );
  9334. data.object.zoom = this.zoom;
  9335. data.object.left = this.left;
  9336. data.object.right = this.right;
  9337. data.object.top = this.top;
  9338. data.object.bottom = this.bottom;
  9339. data.object.near = this.near;
  9340. data.object.far = this.far;
  9341. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9342. return data;
  9343. }
  9344. } );
  9345. /**
  9346. * @author mrdoob / http://mrdoob.com/
  9347. */
  9348. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9349. var mode;
  9350. function setMode( value ) {
  9351. mode = value;
  9352. }
  9353. var type, size;
  9354. function setIndex( index ) {
  9355. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9356. type = gl.UNSIGNED_INT;
  9357. size = 4;
  9358. } else {
  9359. type = gl.UNSIGNED_SHORT;
  9360. size = 2;
  9361. }
  9362. }
  9363. function render( start, count ) {
  9364. gl.drawElements( mode, count, type, start * size );
  9365. infoRender.calls ++;
  9366. infoRender.vertices += count;
  9367. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9368. }
  9369. function renderInstances( geometry, start, count ) {
  9370. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9371. if ( extension === null ) {
  9372. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9373. return;
  9374. }
  9375. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9376. infoRender.calls ++;
  9377. infoRender.vertices += count * geometry.maxInstancedCount;
  9378. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9379. }
  9380. return {
  9381. setMode: setMode,
  9382. setIndex: setIndex,
  9383. render: render,
  9384. renderInstances: renderInstances
  9385. };
  9386. }
  9387. /**
  9388. * @author mrdoob / http://mrdoob.com/
  9389. */
  9390. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9391. var mode;
  9392. function setMode( value ) {
  9393. mode = value;
  9394. }
  9395. function render( start, count ) {
  9396. gl.drawArrays( mode, start, count );
  9397. infoRender.calls ++;
  9398. infoRender.vertices += count;
  9399. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9400. }
  9401. function renderInstances( geometry ) {
  9402. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9403. if ( extension === null ) {
  9404. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9405. return;
  9406. }
  9407. var position = geometry.attributes.position;
  9408. var count = 0;
  9409. if ( (position && position.isInterleavedBufferAttribute) ) {
  9410. count = position.data.count;
  9411. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9412. } else {
  9413. count = position.count;
  9414. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9415. }
  9416. infoRender.calls ++;
  9417. infoRender.vertices += count * geometry.maxInstancedCount;
  9418. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9419. }
  9420. return {
  9421. setMode: setMode,
  9422. render: render,
  9423. renderInstances: renderInstances
  9424. };
  9425. }
  9426. function WebGLLights() {
  9427. var lights = {};
  9428. return {
  9429. get: function ( light ) {
  9430. if ( lights[ light.id ] !== undefined ) {
  9431. return lights[ light.id ];
  9432. }
  9433. var uniforms;
  9434. switch ( light.type ) {
  9435. case 'DirectionalLight':
  9436. uniforms = {
  9437. direction: new Vector3(),
  9438. color: new Color(),
  9439. shadow: false,
  9440. shadowBias: 0,
  9441. shadowRadius: 1,
  9442. shadowMapSize: new Vector2()
  9443. };
  9444. break;
  9445. case 'SpotLight':
  9446. uniforms = {
  9447. position: new Vector3(),
  9448. direction: new Vector3(),
  9449. color: new Color(),
  9450. distance: 0,
  9451. coneCos: 0,
  9452. penumbraCos: 0,
  9453. decay: 0,
  9454. shadow: false,
  9455. shadowBias: 0,
  9456. shadowRadius: 1,
  9457. shadowMapSize: new Vector2()
  9458. };
  9459. break;
  9460. case 'PointLight':
  9461. uniforms = {
  9462. position: new Vector3(),
  9463. color: new Color(),
  9464. distance: 0,
  9465. decay: 0,
  9466. shadow: false,
  9467. shadowBias: 0,
  9468. shadowRadius: 1,
  9469. shadowMapSize: new Vector2()
  9470. };
  9471. break;
  9472. case 'HemisphereLight':
  9473. uniforms = {
  9474. direction: new Vector3(),
  9475. skyColor: new Color(),
  9476. groundColor: new Color()
  9477. };
  9478. break;
  9479. }
  9480. lights[ light.id ] = uniforms;
  9481. return uniforms;
  9482. }
  9483. };
  9484. }
  9485. /**
  9486. * @author mrdoob / http://mrdoob.com/
  9487. */
  9488. function addLineNumbers( string ) {
  9489. var lines = string.split( '\n' );
  9490. for ( var i = 0; i < lines.length; i ++ ) {
  9491. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9492. }
  9493. return lines.join( '\n' );
  9494. }
  9495. function WebGLShader( gl, type, string ) {
  9496. var shader = gl.createShader( type );
  9497. gl.shaderSource( shader, string );
  9498. gl.compileShader( shader );
  9499. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9500. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9501. }
  9502. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9503. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9504. }
  9505. // --enable-privileged-webgl-extension
  9506. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9507. return shader;
  9508. }
  9509. var programIdCount = 0;
  9510. function getEncodingComponents( encoding ) {
  9511. switch ( encoding ) {
  9512. case LinearEncoding:
  9513. return [ 'Linear','( value )' ];
  9514. case sRGBEncoding:
  9515. return [ 'sRGB','( value )' ];
  9516. case RGBEEncoding:
  9517. return [ 'RGBE','( value )' ];
  9518. case RGBM7Encoding:
  9519. return [ 'RGBM','( value, 7.0 )' ];
  9520. case RGBM16Encoding:
  9521. return [ 'RGBM','( value, 16.0 )' ];
  9522. case RGBDEncoding:
  9523. return [ 'RGBD','( value, 256.0 )' ];
  9524. case GammaEncoding:
  9525. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9526. default:
  9527. throw new Error( 'unsupported encoding: ' + encoding );
  9528. }
  9529. }
  9530. function getTexelDecodingFunction( functionName, encoding ) {
  9531. var components = getEncodingComponents( encoding );
  9532. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9533. }
  9534. function getTexelEncodingFunction( functionName, encoding ) {
  9535. var components = getEncodingComponents( encoding );
  9536. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9537. }
  9538. function getToneMappingFunction( functionName, toneMapping ) {
  9539. var toneMappingName;
  9540. switch ( toneMapping ) {
  9541. case LinearToneMapping:
  9542. toneMappingName = "Linear";
  9543. break;
  9544. case ReinhardToneMapping:
  9545. toneMappingName = "Reinhard";
  9546. break;
  9547. case Uncharted2ToneMapping:
  9548. toneMappingName = "Uncharted2";
  9549. break;
  9550. case CineonToneMapping:
  9551. toneMappingName = "OptimizedCineon";
  9552. break;
  9553. default:
  9554. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9555. }
  9556. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9557. }
  9558. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9559. extensions = extensions || {};
  9560. var chunks = [
  9561. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9562. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9563. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9564. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  9565. ];
  9566. return chunks.filter( filterEmptyLine ).join( '\n' );
  9567. }
  9568. function generateDefines( defines ) {
  9569. var chunks = [];
  9570. for ( var name in defines ) {
  9571. var value = defines[ name ];
  9572. if ( value === false ) continue;
  9573. chunks.push( '#define ' + name + ' ' + value );
  9574. }
  9575. return chunks.join( '\n' );
  9576. }
  9577. function fetchAttributeLocations( gl, program, identifiers ) {
  9578. var attributes = {};
  9579. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9580. for ( var i = 0; i < n; i ++ ) {
  9581. var info = gl.getActiveAttrib( program, i );
  9582. var name = info.name;
  9583. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9584. attributes[ name ] = gl.getAttribLocation( program, name );
  9585. }
  9586. return attributes;
  9587. }
  9588. function filterEmptyLine( string ) {
  9589. return string !== '';
  9590. }
  9591. function replaceLightNums( string, parameters ) {
  9592. return string
  9593. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9594. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9595. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9596. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9597. }
  9598. function parseIncludes( string ) {
  9599. var pattern = /#include +<([\w\d.]+)>/g;
  9600. function replace( match, include ) {
  9601. var replace = ShaderChunk[ include ];
  9602. if ( replace === undefined ) {
  9603. throw new Error( 'Can not resolve #include <' + include + '>' );
  9604. }
  9605. return parseIncludes( replace );
  9606. }
  9607. return string.replace( pattern, replace );
  9608. }
  9609. function unrollLoops( string ) {
  9610. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9611. function replace( match, start, end, snippet ) {
  9612. var unroll = '';
  9613. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9614. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9615. }
  9616. return unroll;
  9617. }
  9618. return string.replace( pattern, replace );
  9619. }
  9620. function WebGLProgram( renderer, code, material, parameters ) {
  9621. var gl = renderer.context;
  9622. var extensions = material.extensions;
  9623. var defines = material.defines;
  9624. var vertexShader = material.__webglShader.vertexShader;
  9625. var fragmentShader = material.__webglShader.fragmentShader;
  9626. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9627. if ( parameters.shadowMapType === PCFShadowMap ) {
  9628. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9629. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9630. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9631. }
  9632. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9633. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9634. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9635. if ( parameters.envMap ) {
  9636. switch ( material.envMap.mapping ) {
  9637. case CubeReflectionMapping:
  9638. case CubeRefractionMapping:
  9639. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9640. break;
  9641. case CubeUVReflectionMapping:
  9642. case CubeUVRefractionMapping:
  9643. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9644. break;
  9645. case EquirectangularReflectionMapping:
  9646. case EquirectangularRefractionMapping:
  9647. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9648. break;
  9649. case SphericalReflectionMapping:
  9650. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9651. break;
  9652. }
  9653. switch ( material.envMap.mapping ) {
  9654. case CubeRefractionMapping:
  9655. case EquirectangularRefractionMapping:
  9656. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9657. break;
  9658. }
  9659. switch ( material.combine ) {
  9660. case MultiplyOperation:
  9661. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9662. break;
  9663. case MixOperation:
  9664. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9665. break;
  9666. case AddOperation:
  9667. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9668. break;
  9669. }
  9670. }
  9671. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9672. // console.log( 'building new program ' );
  9673. //
  9674. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9675. var customDefines = generateDefines( defines );
  9676. //
  9677. var program = gl.createProgram();
  9678. var prefixVertex, prefixFragment;
  9679. if ( material.isRawShaderMaterial ) {
  9680. prefixVertex = [
  9681. customDefines,
  9682. '\n'
  9683. ].filter( filterEmptyLine ).join( '\n' );
  9684. prefixFragment = [
  9685. customExtensions,
  9686. customDefines,
  9687. '\n'
  9688. ].filter( filterEmptyLine ).join( '\n' );
  9689. } else {
  9690. prefixVertex = [
  9691. 'precision ' + parameters.precision + ' float;',
  9692. 'precision ' + parameters.precision + ' int;',
  9693. '#define SHADER_NAME ' + material.__webglShader.name,
  9694. customDefines,
  9695. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9696. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9697. '#define MAX_BONES ' + parameters.maxBones,
  9698. parameters.map ? '#define USE_MAP' : '',
  9699. parameters.envMap ? '#define USE_ENVMAP' : '',
  9700. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9701. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9702. parameters.aoMap ? '#define USE_AOMAP' : '',
  9703. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9704. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9705. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9706. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9707. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9708. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9709. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9710. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9711. parameters.vertexColors ? '#define USE_COLOR' : '',
  9712. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9713. parameters.skinning ? '#define USE_SKINNING' : '',
  9714. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9715. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9716. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9717. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9718. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9719. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9720. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9721. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9722. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9723. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9724. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9725. 'uniform mat4 modelMatrix;',
  9726. 'uniform mat4 modelViewMatrix;',
  9727. 'uniform mat4 projectionMatrix;',
  9728. 'uniform mat4 viewMatrix;',
  9729. 'uniform mat3 normalMatrix;',
  9730. 'uniform vec3 cameraPosition;',
  9731. 'attribute vec3 position;',
  9732. 'attribute vec3 normal;',
  9733. 'attribute vec2 uv;',
  9734. '#ifdef USE_COLOR',
  9735. ' attribute vec3 color;',
  9736. '#endif',
  9737. '#ifdef USE_MORPHTARGETS',
  9738. ' attribute vec3 morphTarget0;',
  9739. ' attribute vec3 morphTarget1;',
  9740. ' attribute vec3 morphTarget2;',
  9741. ' attribute vec3 morphTarget3;',
  9742. ' #ifdef USE_MORPHNORMALS',
  9743. ' attribute vec3 morphNormal0;',
  9744. ' attribute vec3 morphNormal1;',
  9745. ' attribute vec3 morphNormal2;',
  9746. ' attribute vec3 morphNormal3;',
  9747. ' #else',
  9748. ' attribute vec3 morphTarget4;',
  9749. ' attribute vec3 morphTarget5;',
  9750. ' attribute vec3 morphTarget6;',
  9751. ' attribute vec3 morphTarget7;',
  9752. ' #endif',
  9753. '#endif',
  9754. '#ifdef USE_SKINNING',
  9755. ' attribute vec4 skinIndex;',
  9756. ' attribute vec4 skinWeight;',
  9757. '#endif',
  9758. '\n'
  9759. ].filter( filterEmptyLine ).join( '\n' );
  9760. prefixFragment = [
  9761. customExtensions,
  9762. 'precision ' + parameters.precision + ' float;',
  9763. 'precision ' + parameters.precision + ' int;',
  9764. '#define SHADER_NAME ' + material.__webglShader.name,
  9765. customDefines,
  9766. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9767. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9768. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9769. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9770. parameters.map ? '#define USE_MAP' : '',
  9771. parameters.envMap ? '#define USE_ENVMAP' : '',
  9772. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9773. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9774. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9775. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9776. parameters.aoMap ? '#define USE_AOMAP' : '',
  9777. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9778. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9779. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9780. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9781. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9782. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9783. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9784. parameters.vertexColors ? '#define USE_COLOR' : '',
  9785. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9786. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9787. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9788. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9789. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9790. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9791. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9792. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9793. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9794. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9795. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9796. 'uniform mat4 viewMatrix;',
  9797. 'uniform vec3 cameraPosition;',
  9798. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9799. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9800. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9801. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  9802. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9803. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9804. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9805. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9806. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9807. '\n'
  9808. ].filter( filterEmptyLine ).join( '\n' );
  9809. }
  9810. vertexShader = parseIncludes( vertexShader, parameters );
  9811. vertexShader = replaceLightNums( vertexShader, parameters );
  9812. fragmentShader = parseIncludes( fragmentShader, parameters );
  9813. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9814. if ( ! material.isShaderMaterial ) {
  9815. vertexShader = unrollLoops( vertexShader );
  9816. fragmentShader = unrollLoops( fragmentShader );
  9817. }
  9818. var vertexGlsl = prefixVertex + vertexShader;
  9819. var fragmentGlsl = prefixFragment + fragmentShader;
  9820. // console.log( '*VERTEX*', vertexGlsl );
  9821. // console.log( '*FRAGMENT*', fragmentGlsl );
  9822. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9823. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9824. gl.attachShader( program, glVertexShader );
  9825. gl.attachShader( program, glFragmentShader );
  9826. // Force a particular attribute to index 0.
  9827. if ( material.index0AttributeName !== undefined ) {
  9828. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9829. } else if ( parameters.morphTargets === true ) {
  9830. // programs with morphTargets displace position out of attribute 0
  9831. gl.bindAttribLocation( program, 0, 'position' );
  9832. }
  9833. gl.linkProgram( program );
  9834. var programLog = gl.getProgramInfoLog( program );
  9835. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9836. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9837. var runnable = true;
  9838. var haveDiagnostics = true;
  9839. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9840. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9841. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9842. runnable = false;
  9843. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9844. } else if ( programLog !== '' ) {
  9845. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9846. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9847. haveDiagnostics = false;
  9848. }
  9849. if ( haveDiagnostics ) {
  9850. this.diagnostics = {
  9851. runnable: runnable,
  9852. material: material,
  9853. programLog: programLog,
  9854. vertexShader: {
  9855. log: vertexLog,
  9856. prefix: prefixVertex
  9857. },
  9858. fragmentShader: {
  9859. log: fragmentLog,
  9860. prefix: prefixFragment
  9861. }
  9862. };
  9863. }
  9864. // clean up
  9865. gl.deleteShader( glVertexShader );
  9866. gl.deleteShader( glFragmentShader );
  9867. // set up caching for uniform locations
  9868. var cachedUniforms;
  9869. this.getUniforms = function() {
  9870. if ( cachedUniforms === undefined ) {
  9871. cachedUniforms =
  9872. new WebGLUniforms( gl, program, renderer );
  9873. }
  9874. return cachedUniforms;
  9875. };
  9876. // set up caching for attribute locations
  9877. var cachedAttributes;
  9878. this.getAttributes = function() {
  9879. if ( cachedAttributes === undefined ) {
  9880. cachedAttributes = fetchAttributeLocations( gl, program );
  9881. }
  9882. return cachedAttributes;
  9883. };
  9884. // free resource
  9885. this.destroy = function() {
  9886. gl.deleteProgram( program );
  9887. this.program = undefined;
  9888. };
  9889. // DEPRECATED
  9890. Object.defineProperties( this, {
  9891. uniforms: {
  9892. get: function() {
  9893. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  9894. return this.getUniforms();
  9895. }
  9896. },
  9897. attributes: {
  9898. get: function() {
  9899. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  9900. return this.getAttributes();
  9901. }
  9902. }
  9903. } );
  9904. //
  9905. this.id = programIdCount ++;
  9906. this.code = code;
  9907. this.usedTimes = 1;
  9908. this.program = program;
  9909. this.vertexShader = glVertexShader;
  9910. this.fragmentShader = glFragmentShader;
  9911. return this;
  9912. }
  9913. function WebGLPrograms( renderer, capabilities ) {
  9914. var programs = [];
  9915. var shaderIDs = {
  9916. MeshDepthMaterial: 'depth',
  9917. MeshNormalMaterial: 'normal',
  9918. MeshBasicMaterial: 'basic',
  9919. MeshLambertMaterial: 'lambert',
  9920. MeshPhongMaterial: 'phong',
  9921. MeshStandardMaterial: 'physical',
  9922. MeshPhysicalMaterial: 'physical',
  9923. LineBasicMaterial: 'basic',
  9924. LineDashedMaterial: 'dashed',
  9925. PointsMaterial: 'points'
  9926. };
  9927. var parameterNames = [
  9928. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  9929. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  9930. "roughnessMap", "metalnessMap",
  9931. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  9932. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  9933. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  9934. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  9935. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  9936. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  9937. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking"
  9938. ];
  9939. function allocateBones( object ) {
  9940. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  9941. return 1024;
  9942. } else {
  9943. // default for when object is not specified
  9944. // ( for example when prebuilding shader to be used with multiple objects )
  9945. //
  9946. // - leave some extra space for other uniforms
  9947. // - limit here is ANGLE's 254 max uniform vectors
  9948. // (up to 54 should be safe)
  9949. var nVertexUniforms = capabilities.maxVertexUniforms;
  9950. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  9951. var maxBones = nVertexMatrices;
  9952. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  9953. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  9954. if ( maxBones < object.skeleton.bones.length ) {
  9955. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  9956. }
  9957. }
  9958. return maxBones;
  9959. }
  9960. }
  9961. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  9962. var encoding;
  9963. if ( ! map ) {
  9964. encoding = LinearEncoding;
  9965. } else if ( (map && map.isTexture) ) {
  9966. encoding = map.encoding;
  9967. } else if ( (map && map.isWebGLRenderTarget) ) {
  9968. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  9969. encoding = map.texture.encoding;
  9970. }
  9971. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  9972. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  9973. encoding = GammaEncoding;
  9974. }
  9975. return encoding;
  9976. }
  9977. this.getParameters = function ( material, lights, fog, nClipPlanes, object ) {
  9978. var shaderID = shaderIDs[ material.type ];
  9979. // heuristics to create shader parameters according to lights in the scene
  9980. // (not to blow over maxLights budget)
  9981. var maxBones = allocateBones( object );
  9982. var precision = renderer.getPrecision();
  9983. if ( material.precision !== null ) {
  9984. precision = capabilities.getMaxPrecision( material.precision );
  9985. if ( precision !== material.precision ) {
  9986. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  9987. }
  9988. }
  9989. var currentRenderTarget = renderer.getCurrentRenderTarget();
  9990. var parameters = {
  9991. shaderID: shaderID,
  9992. precision: precision,
  9993. supportsVertexTextures: capabilities.vertexTextures,
  9994. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  9995. map: !! material.map,
  9996. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  9997. envMap: !! material.envMap,
  9998. envMapMode: material.envMap && material.envMap.mapping,
  9999. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10000. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10001. lightMap: !! material.lightMap,
  10002. aoMap: !! material.aoMap,
  10003. emissiveMap: !! material.emissiveMap,
  10004. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10005. bumpMap: !! material.bumpMap,
  10006. normalMap: !! material.normalMap,
  10007. displacementMap: !! material.displacementMap,
  10008. roughnessMap: !! material.roughnessMap,
  10009. metalnessMap: !! material.metalnessMap,
  10010. specularMap: !! material.specularMap,
  10011. alphaMap: !! material.alphaMap,
  10012. combine: material.combine,
  10013. vertexColors: material.vertexColors,
  10014. fog: !! fog,
  10015. useFog: material.fog,
  10016. fogExp: (fog && fog.isFogExp2),
  10017. flatShading: material.shading === FlatShading,
  10018. sizeAttenuation: material.sizeAttenuation,
  10019. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10020. skinning: material.skinning,
  10021. maxBones: maxBones,
  10022. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10023. morphTargets: material.morphTargets,
  10024. morphNormals: material.morphNormals,
  10025. maxMorphTargets: renderer.maxMorphTargets,
  10026. maxMorphNormals: renderer.maxMorphNormals,
  10027. numDirLights: lights.directional.length,
  10028. numPointLights: lights.point.length,
  10029. numSpotLights: lights.spot.length,
  10030. numHemiLights: lights.hemi.length,
  10031. numClippingPlanes: nClipPlanes,
  10032. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10033. shadowMapType: renderer.shadowMap.type,
  10034. toneMapping: renderer.toneMapping,
  10035. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10036. premultipliedAlpha: material.premultipliedAlpha,
  10037. alphaTest: material.alphaTest,
  10038. doubleSided: material.side === DoubleSide,
  10039. flipSided: material.side === BackSide,
  10040. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10041. };
  10042. return parameters;
  10043. };
  10044. this.getProgramCode = function ( material, parameters ) {
  10045. var array = [];
  10046. if ( parameters.shaderID ) {
  10047. array.push( parameters.shaderID );
  10048. } else {
  10049. array.push( material.fragmentShader );
  10050. array.push( material.vertexShader );
  10051. }
  10052. if ( material.defines !== undefined ) {
  10053. for ( var name in material.defines ) {
  10054. array.push( name );
  10055. array.push( material.defines[ name ] );
  10056. }
  10057. }
  10058. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10059. array.push( parameters[ parameterNames[ i ] ] );
  10060. }
  10061. return array.join();
  10062. };
  10063. this.acquireProgram = function ( material, parameters, code ) {
  10064. var program;
  10065. // Check if code has been already compiled
  10066. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10067. var programInfo = programs[ p ];
  10068. if ( programInfo.code === code ) {
  10069. program = programInfo;
  10070. ++ program.usedTimes;
  10071. break;
  10072. }
  10073. }
  10074. if ( program === undefined ) {
  10075. program = new WebGLProgram( renderer, code, material, parameters );
  10076. programs.push( program );
  10077. }
  10078. return program;
  10079. };
  10080. this.releaseProgram = function( program ) {
  10081. if ( -- program.usedTimes === 0 ) {
  10082. // Remove from unordered set
  10083. var i = programs.indexOf( program );
  10084. programs[ i ] = programs[ programs.length - 1 ];
  10085. programs.pop();
  10086. // Free WebGL resources
  10087. program.destroy();
  10088. }
  10089. };
  10090. // Exposed for resource monitoring & error feedback via renderer.info:
  10091. this.programs = programs;
  10092. }
  10093. function WebGLGeometries( gl, properties, info ) {
  10094. var geometries = {};
  10095. function onGeometryDispose( event ) {
  10096. var geometry = event.target;
  10097. var buffergeometry = geometries[ geometry.id ];
  10098. if ( buffergeometry.index !== null ) {
  10099. deleteAttribute( buffergeometry.index );
  10100. }
  10101. deleteAttributes( buffergeometry.attributes );
  10102. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10103. delete geometries[ geometry.id ];
  10104. // TODO
  10105. var property = properties.get( geometry );
  10106. if ( property.wireframe ) {
  10107. deleteAttribute( property.wireframe );
  10108. }
  10109. properties.delete( geometry );
  10110. var bufferproperty = properties.get( buffergeometry );
  10111. if ( bufferproperty.wireframe ) {
  10112. deleteAttribute( bufferproperty.wireframe );
  10113. }
  10114. properties.delete( buffergeometry );
  10115. //
  10116. info.memory.geometries --;
  10117. }
  10118. function getAttributeBuffer( attribute ) {
  10119. if ( attribute.isInterleavedBufferAttribute ) {
  10120. return properties.get( attribute.data ).__webglBuffer;
  10121. }
  10122. return properties.get( attribute ).__webglBuffer;
  10123. }
  10124. function deleteAttribute( attribute ) {
  10125. var buffer = getAttributeBuffer( attribute );
  10126. if ( buffer !== undefined ) {
  10127. gl.deleteBuffer( buffer );
  10128. removeAttributeBuffer( attribute );
  10129. }
  10130. }
  10131. function deleteAttributes( attributes ) {
  10132. for ( var name in attributes ) {
  10133. deleteAttribute( attributes[ name ] );
  10134. }
  10135. }
  10136. function removeAttributeBuffer( attribute ) {
  10137. if ( attribute.isInterleavedBufferAttribute ) {
  10138. properties.delete( attribute.data );
  10139. } else {
  10140. properties.delete( attribute );
  10141. }
  10142. }
  10143. return {
  10144. get: function ( object ) {
  10145. var geometry = object.geometry;
  10146. if ( geometries[ geometry.id ] !== undefined ) {
  10147. return geometries[ geometry.id ];
  10148. }
  10149. geometry.addEventListener( 'dispose', onGeometryDispose );
  10150. var buffergeometry;
  10151. if ( geometry.isBufferGeometry ) {
  10152. buffergeometry = geometry;
  10153. } else if ( geometry.isGeometry ) {
  10154. if ( geometry._bufferGeometry === undefined ) {
  10155. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10156. }
  10157. buffergeometry = geometry._bufferGeometry;
  10158. }
  10159. geometries[ geometry.id ] = buffergeometry;
  10160. info.memory.geometries ++;
  10161. return buffergeometry;
  10162. }
  10163. };
  10164. }
  10165. function WebGLObjects( gl, properties, info ) {
  10166. var geometries = new WebGLGeometries( gl, properties, info );
  10167. //
  10168. function update( object ) {
  10169. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10170. var geometry = geometries.get( object );
  10171. if ( object.geometry.isGeometry ) {
  10172. geometry.updateFromObject( object );
  10173. }
  10174. var index = geometry.index;
  10175. var attributes = geometry.attributes;
  10176. if ( index !== null ) {
  10177. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10178. }
  10179. for ( var name in attributes ) {
  10180. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10181. }
  10182. // morph targets
  10183. var morphAttributes = geometry.morphAttributes;
  10184. for ( var name in morphAttributes ) {
  10185. var array = morphAttributes[ name ];
  10186. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10187. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10188. }
  10189. }
  10190. return geometry;
  10191. }
  10192. function updateAttribute( attribute, bufferType ) {
  10193. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10194. var attributeProperties = properties.get( data );
  10195. if ( attributeProperties.__webglBuffer === undefined ) {
  10196. createBuffer( attributeProperties, data, bufferType );
  10197. } else if ( attributeProperties.version !== data.version ) {
  10198. updateBuffer( attributeProperties, data, bufferType );
  10199. }
  10200. }
  10201. function createBuffer( attributeProperties, data, bufferType ) {
  10202. attributeProperties.__webglBuffer = gl.createBuffer();
  10203. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10204. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10205. gl.bufferData( bufferType, data.array, usage );
  10206. attributeProperties.version = data.version;
  10207. }
  10208. function updateBuffer( attributeProperties, data, bufferType ) {
  10209. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10210. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  10211. // Not using update ranges
  10212. gl.bufferSubData( bufferType, 0, data.array );
  10213. } else if ( data.updateRange.count === 0 ) {
  10214. 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.' );
  10215. } else {
  10216. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10217. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10218. data.updateRange.count = 0; // reset range
  10219. }
  10220. attributeProperties.version = data.version;
  10221. }
  10222. function getAttributeBuffer( attribute ) {
  10223. if ( attribute.isInterleavedBufferAttribute ) {
  10224. return properties.get( attribute.data ).__webglBuffer;
  10225. }
  10226. return properties.get( attribute ).__webglBuffer;
  10227. }
  10228. function getWireframeAttribute( geometry ) {
  10229. var property = properties.get( geometry );
  10230. if ( property.wireframe !== undefined ) {
  10231. return property.wireframe;
  10232. }
  10233. var indices = [];
  10234. var index = geometry.index;
  10235. var attributes = geometry.attributes;
  10236. var position = attributes.position;
  10237. // console.time( 'wireframe' );
  10238. if ( index !== null ) {
  10239. var edges = {};
  10240. var array = index.array;
  10241. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10242. var a = array[ i + 0 ];
  10243. var b = array[ i + 1 ];
  10244. var c = array[ i + 2 ];
  10245. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  10246. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  10247. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  10248. }
  10249. } else {
  10250. var array = attributes.position.array;
  10251. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10252. var a = i + 0;
  10253. var b = i + 1;
  10254. var c = i + 2;
  10255. indices.push( a, b, b, c, c, a );
  10256. }
  10257. }
  10258. // console.timeEnd( 'wireframe' );
  10259. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10260. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10261. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10262. property.wireframe = attribute;
  10263. return attribute;
  10264. }
  10265. function checkEdge( edges, a, b ) {
  10266. if ( a > b ) {
  10267. var tmp = a;
  10268. a = b;
  10269. b = tmp;
  10270. }
  10271. var list = edges[ a ];
  10272. if ( list === undefined ) {
  10273. edges[ a ] = [ b ];
  10274. return true;
  10275. } else if ( list.indexOf( b ) === -1 ) {
  10276. list.push( b );
  10277. return true;
  10278. }
  10279. return false;
  10280. }
  10281. return {
  10282. getAttributeBuffer: getAttributeBuffer,
  10283. getWireframeAttribute: getWireframeAttribute,
  10284. update: update
  10285. };
  10286. }
  10287. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10288. var _infoMemory = info.memory;
  10289. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10290. //
  10291. function clampToMaxSize( image, maxSize ) {
  10292. if ( image.width > maxSize || image.height > maxSize ) {
  10293. // Warning: Scaling through the canvas will only work with images that use
  10294. // premultiplied alpha.
  10295. var scale = maxSize / Math.max( image.width, image.height );
  10296. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10297. canvas.width = Math.floor( image.width * scale );
  10298. canvas.height = Math.floor( image.height * scale );
  10299. var context = canvas.getContext( '2d' );
  10300. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10301. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10302. return canvas;
  10303. }
  10304. return image;
  10305. }
  10306. function isPowerOfTwo( image ) {
  10307. return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height );
  10308. }
  10309. function makePowerOfTwo( image ) {
  10310. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10311. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10312. canvas.width = exports.Math.nearestPowerOfTwo( image.width );
  10313. canvas.height = exports.Math.nearestPowerOfTwo( image.height );
  10314. var context = canvas.getContext( '2d' );
  10315. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10316. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10317. return canvas;
  10318. }
  10319. return image;
  10320. }
  10321. function textureNeedsPowerOfTwo( texture ) {
  10322. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  10323. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  10324. return false;
  10325. }
  10326. // Fallback filters for non-power-of-2 textures
  10327. function filterFallback( f ) {
  10328. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10329. return _gl.NEAREST;
  10330. }
  10331. return _gl.LINEAR;
  10332. }
  10333. //
  10334. function onTextureDispose( event ) {
  10335. var texture = event.target;
  10336. texture.removeEventListener( 'dispose', onTextureDispose );
  10337. deallocateTexture( texture );
  10338. _infoMemory.textures --;
  10339. }
  10340. function onRenderTargetDispose( event ) {
  10341. var renderTarget = event.target;
  10342. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10343. deallocateRenderTarget( renderTarget );
  10344. _infoMemory.textures --;
  10345. }
  10346. //
  10347. function deallocateTexture( texture ) {
  10348. var textureProperties = properties.get( texture );
  10349. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10350. // cube texture
  10351. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10352. } else {
  10353. // 2D texture
  10354. if ( textureProperties.__webglInit === undefined ) return;
  10355. _gl.deleteTexture( textureProperties.__webglTexture );
  10356. }
  10357. // remove all webgl properties
  10358. properties.delete( texture );
  10359. }
  10360. function deallocateRenderTarget( renderTarget ) {
  10361. var renderTargetProperties = properties.get( renderTarget );
  10362. var textureProperties = properties.get( renderTarget.texture );
  10363. if ( ! renderTarget ) return;
  10364. if ( textureProperties.__webglTexture !== undefined ) {
  10365. _gl.deleteTexture( textureProperties.__webglTexture );
  10366. }
  10367. if ( renderTarget.depthTexture ) {
  10368. renderTarget.depthTexture.dispose();
  10369. }
  10370. if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) {
  10371. for ( var i = 0; i < 6; i ++ ) {
  10372. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10373. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10374. }
  10375. } else {
  10376. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10377. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10378. }
  10379. properties.delete( renderTarget.texture );
  10380. properties.delete( renderTarget );
  10381. }
  10382. //
  10383. function setTexture2D( texture, slot ) {
  10384. var textureProperties = properties.get( texture );
  10385. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10386. var image = texture.image;
  10387. if ( image === undefined ) {
  10388. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10389. } else if ( image.complete === false ) {
  10390. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10391. } else {
  10392. uploadTexture( textureProperties, texture, slot );
  10393. return;
  10394. }
  10395. }
  10396. state.activeTexture( _gl.TEXTURE0 + slot );
  10397. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10398. }
  10399. function setTextureCube( texture, slot ) {
  10400. var textureProperties = properties.get( texture );
  10401. if ( texture.image.length === 6 ) {
  10402. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10403. if ( ! textureProperties.__image__webglTextureCube ) {
  10404. texture.addEventListener( 'dispose', onTextureDispose );
  10405. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10406. _infoMemory.textures ++;
  10407. }
  10408. state.activeTexture( _gl.TEXTURE0 + slot );
  10409. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10410. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10411. var isCompressed = (texture && texture.isCompressedTexture);
  10412. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  10413. var cubeImage = [];
  10414. for ( var i = 0; i < 6; i ++ ) {
  10415. if ( ! isCompressed && ! isDataTexture ) {
  10416. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10417. } else {
  10418. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10419. }
  10420. }
  10421. var image = cubeImage[ 0 ],
  10422. isPowerOfTwoImage = isPowerOfTwo( image ),
  10423. glFormat = paramThreeToGL( texture.format ),
  10424. glType = paramThreeToGL( texture.type );
  10425. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10426. for ( var i = 0; i < 6; i ++ ) {
  10427. if ( ! isCompressed ) {
  10428. if ( isDataTexture ) {
  10429. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10430. } else {
  10431. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10432. }
  10433. } else {
  10434. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10435. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10436. mipmap = mipmaps[ j ];
  10437. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10438. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10439. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10440. } else {
  10441. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10442. }
  10443. } else {
  10444. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10445. }
  10446. }
  10447. }
  10448. }
  10449. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10450. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10451. }
  10452. textureProperties.__version = texture.version;
  10453. if ( texture.onUpdate ) texture.onUpdate( texture );
  10454. } else {
  10455. state.activeTexture( _gl.TEXTURE0 + slot );
  10456. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10457. }
  10458. }
  10459. }
  10460. function setTextureCubeDynamic( texture, slot ) {
  10461. state.activeTexture( _gl.TEXTURE0 + slot );
  10462. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10463. }
  10464. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10465. var extension;
  10466. if ( isPowerOfTwoImage ) {
  10467. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10468. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10469. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10470. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10471. } else {
  10472. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10473. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10474. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10475. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10476. }
  10477. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10478. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10479. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10480. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10481. }
  10482. }
  10483. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10484. if ( extension ) {
  10485. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10486. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10487. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10488. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10489. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10490. }
  10491. }
  10492. }
  10493. function uploadTexture( textureProperties, texture, slot ) {
  10494. if ( textureProperties.__webglInit === undefined ) {
  10495. textureProperties.__webglInit = true;
  10496. texture.addEventListener( 'dispose', onTextureDispose );
  10497. textureProperties.__webglTexture = _gl.createTexture();
  10498. _infoMemory.textures ++;
  10499. }
  10500. state.activeTexture( _gl.TEXTURE0 + slot );
  10501. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10502. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10503. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10504. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10505. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10506. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10507. image = makePowerOfTwo( image );
  10508. }
  10509. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10510. glFormat = paramThreeToGL( texture.format ),
  10511. glType = paramThreeToGL( texture.type );
  10512. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10513. var mipmap, mipmaps = texture.mipmaps;
  10514. if ( (texture && texture.isDepthTexture) ) {
  10515. // populate depth texture with dummy data
  10516. var internalFormat = _gl.DEPTH_COMPONENT;
  10517. if ( texture.type === FloatType ) {
  10518. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10519. internalFormat = _gl.DEPTH_COMPONENT32F;
  10520. } else if ( _isWebGL2 ) {
  10521. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10522. internalFormat = _gl.DEPTH_COMPONENT16;
  10523. }
  10524. // Depth stencil textures need the DEPTH_STENCIL internal format
  10525. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10526. if ( texture.format === DepthStencilFormat ) {
  10527. internalFormat = _gl.DEPTH_STENCIL;
  10528. }
  10529. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10530. } else if ( (texture && texture.isDataTexture) ) {
  10531. // use manually created mipmaps if available
  10532. // if there are no manual mipmaps
  10533. // set 0 level mipmap and then use GL to generate other mipmap levels
  10534. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10535. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10536. mipmap = mipmaps[ i ];
  10537. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10538. }
  10539. texture.generateMipmaps = false;
  10540. } else {
  10541. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10542. }
  10543. } else if ( (texture && texture.isCompressedTexture) ) {
  10544. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10545. mipmap = mipmaps[ i ];
  10546. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10547. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10548. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10549. } else {
  10550. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10551. }
  10552. } else {
  10553. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10554. }
  10555. }
  10556. } else {
  10557. // regular Texture (image, video, canvas)
  10558. // use manually created mipmaps if available
  10559. // if there are no manual mipmaps
  10560. // set 0 level mipmap and then use GL to generate other mipmap levels
  10561. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10562. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10563. mipmap = mipmaps[ i ];
  10564. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10565. }
  10566. texture.generateMipmaps = false;
  10567. } else {
  10568. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10569. }
  10570. }
  10571. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10572. textureProperties.__version = texture.version;
  10573. if ( texture.onUpdate ) texture.onUpdate( texture );
  10574. }
  10575. // Render targets
  10576. // Setup storage for target texture and bind it to correct framebuffer
  10577. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10578. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10579. var glType = paramThreeToGL( renderTarget.texture.type );
  10580. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10581. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10582. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10583. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10584. }
  10585. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10586. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10587. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10588. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10589. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10590. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10591. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10592. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10593. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10594. } else {
  10595. // FIXME: We don't support !depth !stencil
  10596. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10597. }
  10598. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10599. }
  10600. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10601. function setupDepthTexture( framebuffer, renderTarget ) {
  10602. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10603. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10604. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10605. if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) {
  10606. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10607. }
  10608. // upload an empty depth texture with framebuffer size
  10609. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10610. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10611. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10612. renderTarget.depthTexture.image.width = renderTarget.width;
  10613. renderTarget.depthTexture.image.height = renderTarget.height;
  10614. renderTarget.depthTexture.needsUpdate = true;
  10615. }
  10616. setTexture2D( renderTarget.depthTexture, 0 );
  10617. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10618. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10619. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10620. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10621. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10622. } else {
  10623. throw new Error('Unknown depthTexture format')
  10624. }
  10625. }
  10626. // Setup GL resources for a non-texture depth buffer
  10627. function setupDepthRenderbuffer( renderTarget ) {
  10628. var renderTargetProperties = properties.get( renderTarget );
  10629. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10630. if ( renderTarget.depthTexture ) {
  10631. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10632. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10633. } else {
  10634. if ( isCube ) {
  10635. renderTargetProperties.__webglDepthbuffer = [];
  10636. for ( var i = 0; i < 6; i ++ ) {
  10637. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10638. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10639. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10640. }
  10641. } else {
  10642. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10643. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10644. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10645. }
  10646. }
  10647. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10648. }
  10649. // Set up GL resources for the render target
  10650. function setupRenderTarget( renderTarget ) {
  10651. var renderTargetProperties = properties.get( renderTarget );
  10652. var textureProperties = properties.get( renderTarget.texture );
  10653. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10654. textureProperties.__webglTexture = _gl.createTexture();
  10655. _infoMemory.textures ++;
  10656. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  10657. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10658. // Setup framebuffer
  10659. if ( isCube ) {
  10660. renderTargetProperties.__webglFramebuffer = [];
  10661. for ( var i = 0; i < 6; i ++ ) {
  10662. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10663. }
  10664. } else {
  10665. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10666. }
  10667. // Setup color buffer
  10668. if ( isCube ) {
  10669. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10670. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10671. for ( var i = 0; i < 6; i ++ ) {
  10672. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10673. }
  10674. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10675. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10676. } else {
  10677. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10678. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10679. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10680. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10681. state.bindTexture( _gl.TEXTURE_2D, null );
  10682. }
  10683. // Setup depth and stencil buffers
  10684. if ( renderTarget.depthBuffer ) {
  10685. setupDepthRenderbuffer( renderTarget );
  10686. }
  10687. }
  10688. function updateRenderTargetMipmap( renderTarget ) {
  10689. var texture = renderTarget.texture;
  10690. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10691. texture.minFilter !== NearestFilter &&
  10692. texture.minFilter !== LinearFilter ) {
  10693. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10694. var webglTexture = properties.get( texture ).__webglTexture;
  10695. state.bindTexture( target, webglTexture );
  10696. _gl.generateMipmap( target );
  10697. state.bindTexture( target, null );
  10698. }
  10699. }
  10700. this.setTexture2D = setTexture2D;
  10701. this.setTextureCube = setTextureCube;
  10702. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10703. this.setupRenderTarget = setupRenderTarget;
  10704. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10705. }
  10706. /**
  10707. * @author fordacious / fordacious.github.io
  10708. */
  10709. function WebGLProperties() {
  10710. var properties = {};
  10711. return {
  10712. get: function ( object ) {
  10713. var uuid = object.uuid;
  10714. var map = properties[ uuid ];
  10715. if ( map === undefined ) {
  10716. map = {};
  10717. properties[ uuid ] = map;
  10718. }
  10719. return map;
  10720. },
  10721. delete: function ( object ) {
  10722. delete properties[ object.uuid ];
  10723. },
  10724. clear: function () {
  10725. properties = {};
  10726. }
  10727. };
  10728. }
  10729. function WebGLState( gl, extensions, paramThreeToGL ) {
  10730. function ColorBuffer() {
  10731. var locked = false;
  10732. var color = new Vector4();
  10733. var currentColorMask = null;
  10734. var currentColorClear = new Vector4();
  10735. return {
  10736. setMask: function ( colorMask ) {
  10737. if ( currentColorMask !== colorMask && ! locked ) {
  10738. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10739. currentColorMask = colorMask;
  10740. }
  10741. },
  10742. setLocked: function ( lock ) {
  10743. locked = lock;
  10744. },
  10745. setClear: function ( r, g, b, a ) {
  10746. color.set( r, g, b, a );
  10747. if ( currentColorClear.equals( color ) === false ) {
  10748. gl.clearColor( r, g, b, a );
  10749. currentColorClear.copy( color );
  10750. }
  10751. },
  10752. reset: function () {
  10753. locked = false;
  10754. currentColorMask = null;
  10755. currentColorClear.set( 0, 0, 0, 1 );
  10756. }
  10757. };
  10758. }
  10759. function DepthBuffer() {
  10760. var locked = false;
  10761. var currentDepthMask = null;
  10762. var currentDepthFunc = null;
  10763. var currentDepthClear = null;
  10764. return {
  10765. setTest: function ( depthTest ) {
  10766. if ( depthTest ) {
  10767. enable( gl.DEPTH_TEST );
  10768. } else {
  10769. disable( gl.DEPTH_TEST );
  10770. }
  10771. },
  10772. setMask: function ( depthMask ) {
  10773. if ( currentDepthMask !== depthMask && ! locked ) {
  10774. gl.depthMask( depthMask );
  10775. currentDepthMask = depthMask;
  10776. }
  10777. },
  10778. setFunc: function ( depthFunc ) {
  10779. if ( currentDepthFunc !== depthFunc ) {
  10780. if ( depthFunc ) {
  10781. switch ( depthFunc ) {
  10782. case NeverDepth:
  10783. gl.depthFunc( gl.NEVER );
  10784. break;
  10785. case AlwaysDepth:
  10786. gl.depthFunc( gl.ALWAYS );
  10787. break;
  10788. case LessDepth:
  10789. gl.depthFunc( gl.LESS );
  10790. break;
  10791. case LessEqualDepth:
  10792. gl.depthFunc( gl.LEQUAL );
  10793. break;
  10794. case EqualDepth:
  10795. gl.depthFunc( gl.EQUAL );
  10796. break;
  10797. case GreaterEqualDepth:
  10798. gl.depthFunc( gl.GEQUAL );
  10799. break;
  10800. case GreaterDepth:
  10801. gl.depthFunc( gl.GREATER );
  10802. break;
  10803. case NotEqualDepth:
  10804. gl.depthFunc( gl.NOTEQUAL );
  10805. break;
  10806. default:
  10807. gl.depthFunc( gl.LEQUAL );
  10808. }
  10809. } else {
  10810. gl.depthFunc( gl.LEQUAL );
  10811. }
  10812. currentDepthFunc = depthFunc;
  10813. }
  10814. },
  10815. setLocked: function ( lock ) {
  10816. locked = lock;
  10817. },
  10818. setClear: function ( depth ) {
  10819. if ( currentDepthClear !== depth ) {
  10820. gl.clearDepth( depth );
  10821. currentDepthClear = depth;
  10822. }
  10823. },
  10824. reset: function () {
  10825. locked = false;
  10826. currentDepthMask = null;
  10827. currentDepthFunc = null;
  10828. currentDepthClear = null;
  10829. }
  10830. };
  10831. }
  10832. function StencilBuffer() {
  10833. var locked = false;
  10834. var currentStencilMask = null;
  10835. var currentStencilFunc = null;
  10836. var currentStencilRef = null;
  10837. var currentStencilFuncMask = null;
  10838. var currentStencilFail = null;
  10839. var currentStencilZFail = null;
  10840. var currentStencilZPass = null;
  10841. var currentStencilClear = null;
  10842. return {
  10843. setTest: function ( stencilTest ) {
  10844. if ( stencilTest ) {
  10845. enable( gl.STENCIL_TEST );
  10846. } else {
  10847. disable( gl.STENCIL_TEST );
  10848. }
  10849. },
  10850. setMask: function ( stencilMask ) {
  10851. if ( currentStencilMask !== stencilMask && ! locked ) {
  10852. gl.stencilMask( stencilMask );
  10853. currentStencilMask = stencilMask;
  10854. }
  10855. },
  10856. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  10857. if ( currentStencilFunc !== stencilFunc ||
  10858. currentStencilRef !== stencilRef ||
  10859. currentStencilFuncMask !== stencilMask ) {
  10860. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  10861. currentStencilFunc = stencilFunc;
  10862. currentStencilRef = stencilRef;
  10863. currentStencilFuncMask = stencilMask;
  10864. }
  10865. },
  10866. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  10867. if ( currentStencilFail !== stencilFail ||
  10868. currentStencilZFail !== stencilZFail ||
  10869. currentStencilZPass !== stencilZPass ) {
  10870. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  10871. currentStencilFail = stencilFail;
  10872. currentStencilZFail = stencilZFail;
  10873. currentStencilZPass = stencilZPass;
  10874. }
  10875. },
  10876. setLocked: function ( lock ) {
  10877. locked = lock;
  10878. },
  10879. setClear: function ( stencil ) {
  10880. if ( currentStencilClear !== stencil ) {
  10881. gl.clearStencil( stencil );
  10882. currentStencilClear = stencil;
  10883. }
  10884. },
  10885. reset: function () {
  10886. locked = false;
  10887. currentStencilMask = null;
  10888. currentStencilFunc = null;
  10889. currentStencilRef = null;
  10890. currentStencilFuncMask = null;
  10891. currentStencilFail = null;
  10892. currentStencilZFail = null;
  10893. currentStencilZPass = null;
  10894. currentStencilClear = null;
  10895. }
  10896. };
  10897. }
  10898. //
  10899. var colorBuffer = new ColorBuffer();
  10900. var depthBuffer = new DepthBuffer();
  10901. var stencilBuffer = new StencilBuffer();
  10902. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  10903. var newAttributes = new Uint8Array( maxVertexAttributes );
  10904. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  10905. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  10906. var capabilities = {};
  10907. var compressedTextureFormats = null;
  10908. var currentBlending = null;
  10909. var currentBlendEquation = null;
  10910. var currentBlendSrc = null;
  10911. var currentBlendDst = null;
  10912. var currentBlendEquationAlpha = null;
  10913. var currentBlendSrcAlpha = null;
  10914. var currentBlendDstAlpha = null;
  10915. var currentPremultipledAlpha = false;
  10916. var currentFlipSided = null;
  10917. var currentCullFace = null;
  10918. var currentLineWidth = null;
  10919. var currentPolygonOffsetFactor = null;
  10920. var currentPolygonOffsetUnits = null;
  10921. var currentScissorTest = null;
  10922. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  10923. var currentTextureSlot = null;
  10924. var currentBoundTextures = {};
  10925. var currentScissor = new Vector4();
  10926. var currentViewport = new Vector4();
  10927. function createTexture( type, target, count ) {
  10928. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  10929. var texture = gl.createTexture();
  10930. gl.bindTexture( type, texture );
  10931. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  10932. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  10933. for ( var i = 0; i < count; i ++ ) {
  10934. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  10935. }
  10936. return texture;
  10937. }
  10938. var emptyTextures = {};
  10939. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  10940. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  10941. //
  10942. function init() {
  10943. clearColor( 0, 0, 0, 1 );
  10944. clearDepth( 1 );
  10945. clearStencil( 0 );
  10946. enable( gl.DEPTH_TEST );
  10947. setDepthFunc( LessEqualDepth );
  10948. setFlipSided( false );
  10949. setCullFace( CullFaceBack );
  10950. enable( gl.CULL_FACE );
  10951. enable( gl.BLEND );
  10952. setBlending( NormalBlending );
  10953. }
  10954. function initAttributes() {
  10955. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  10956. newAttributes[ i ] = 0;
  10957. }
  10958. }
  10959. function enableAttribute( attribute ) {
  10960. newAttributes[ attribute ] = 1;
  10961. if ( enabledAttributes[ attribute ] === 0 ) {
  10962. gl.enableVertexAttribArray( attribute );
  10963. enabledAttributes[ attribute ] = 1;
  10964. }
  10965. if ( attributeDivisors[ attribute ] !== 0 ) {
  10966. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10967. extension.vertexAttribDivisorANGLE( attribute, 0 );
  10968. attributeDivisors[ attribute ] = 0;
  10969. }
  10970. }
  10971. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  10972. newAttributes[ attribute ] = 1;
  10973. if ( enabledAttributes[ attribute ] === 0 ) {
  10974. gl.enableVertexAttribArray( attribute );
  10975. enabledAttributes[ attribute ] = 1;
  10976. }
  10977. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  10978. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  10979. attributeDivisors[ attribute ] = meshPerAttribute;
  10980. }
  10981. }
  10982. function disableUnusedAttributes() {
  10983. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  10984. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  10985. gl.disableVertexAttribArray( i );
  10986. enabledAttributes[ i ] = 0;
  10987. }
  10988. }
  10989. }
  10990. function enable( id ) {
  10991. if ( capabilities[ id ] !== true ) {
  10992. gl.enable( id );
  10993. capabilities[ id ] = true;
  10994. }
  10995. }
  10996. function disable( id ) {
  10997. if ( capabilities[ id ] !== false ) {
  10998. gl.disable( id );
  10999. capabilities[ id ] = false;
  11000. }
  11001. }
  11002. function getCompressedTextureFormats() {
  11003. if ( compressedTextureFormats === null ) {
  11004. compressedTextureFormats = [];
  11005. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11006. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11007. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11008. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11009. for ( var i = 0; i < formats.length; i ++ ) {
  11010. compressedTextureFormats.push( formats[ i ] );
  11011. }
  11012. }
  11013. }
  11014. return compressedTextureFormats;
  11015. }
  11016. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11017. if ( blending !== NoBlending ) {
  11018. enable( gl.BLEND );
  11019. } else {
  11020. disable( gl.BLEND );
  11021. currentBlending = blending; // no blending, that is
  11022. return;
  11023. }
  11024. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11025. if ( blending === AdditiveBlending ) {
  11026. if ( premultipliedAlpha ) {
  11027. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11028. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11029. } else {
  11030. gl.blendEquation( gl.FUNC_ADD );
  11031. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11032. }
  11033. } else if ( blending === SubtractiveBlending ) {
  11034. if ( premultipliedAlpha ) {
  11035. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11036. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11037. } else {
  11038. gl.blendEquation( gl.FUNC_ADD );
  11039. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11040. }
  11041. } else if ( blending === MultiplyBlending ) {
  11042. if ( premultipliedAlpha ) {
  11043. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11044. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11045. } else {
  11046. gl.blendEquation( gl.FUNC_ADD );
  11047. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11048. }
  11049. } else {
  11050. if ( premultipliedAlpha ) {
  11051. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11052. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11053. } else {
  11054. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11055. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11056. }
  11057. }
  11058. currentBlending = blending;
  11059. currentPremultipledAlpha = premultipliedAlpha;
  11060. }
  11061. if ( blending === CustomBlending ) {
  11062. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11063. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11064. blendDstAlpha = blendDstAlpha || blendDst;
  11065. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11066. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11067. currentBlendEquation = blendEquation;
  11068. currentBlendEquationAlpha = blendEquationAlpha;
  11069. }
  11070. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11071. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11072. currentBlendSrc = blendSrc;
  11073. currentBlendDst = blendDst;
  11074. currentBlendSrcAlpha = blendSrcAlpha;
  11075. currentBlendDstAlpha = blendDstAlpha;
  11076. }
  11077. } else {
  11078. currentBlendEquation = null;
  11079. currentBlendSrc = null;
  11080. currentBlendDst = null;
  11081. currentBlendEquationAlpha = null;
  11082. currentBlendSrcAlpha = null;
  11083. currentBlendDstAlpha = null;
  11084. }
  11085. }
  11086. // TODO Deprecate
  11087. function setColorWrite( colorWrite ) {
  11088. colorBuffer.setMask( colorWrite );
  11089. }
  11090. function setDepthTest( depthTest ) {
  11091. depthBuffer.setTest( depthTest );
  11092. }
  11093. function setDepthWrite( depthWrite ) {
  11094. depthBuffer.setMask( depthWrite );
  11095. }
  11096. function setDepthFunc( depthFunc ) {
  11097. depthBuffer.setFunc( depthFunc );
  11098. }
  11099. function setStencilTest( stencilTest ) {
  11100. stencilBuffer.setTest( stencilTest );
  11101. }
  11102. function setStencilWrite( stencilWrite ) {
  11103. stencilBuffer.setMask( stencilWrite );
  11104. }
  11105. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11106. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11107. }
  11108. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11109. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11110. }
  11111. //
  11112. function setFlipSided( flipSided ) {
  11113. if ( currentFlipSided !== flipSided ) {
  11114. if ( flipSided ) {
  11115. gl.frontFace( gl.CW );
  11116. } else {
  11117. gl.frontFace( gl.CCW );
  11118. }
  11119. currentFlipSided = flipSided;
  11120. }
  11121. }
  11122. function setCullFace( cullFace ) {
  11123. if ( cullFace !== CullFaceNone ) {
  11124. enable( gl.CULL_FACE );
  11125. if ( cullFace !== currentCullFace ) {
  11126. if ( cullFace === CullFaceBack ) {
  11127. gl.cullFace( gl.BACK );
  11128. } else if ( cullFace === CullFaceFront ) {
  11129. gl.cullFace( gl.FRONT );
  11130. } else {
  11131. gl.cullFace( gl.FRONT_AND_BACK );
  11132. }
  11133. }
  11134. } else {
  11135. disable( gl.CULL_FACE );
  11136. }
  11137. currentCullFace = cullFace;
  11138. }
  11139. function setLineWidth( width ) {
  11140. if ( width !== currentLineWidth ) {
  11141. gl.lineWidth( width );
  11142. currentLineWidth = width;
  11143. }
  11144. }
  11145. function setPolygonOffset( polygonOffset, factor, units ) {
  11146. if ( polygonOffset ) {
  11147. enable( gl.POLYGON_OFFSET_FILL );
  11148. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11149. gl.polygonOffset( factor, units );
  11150. currentPolygonOffsetFactor = factor;
  11151. currentPolygonOffsetUnits = units;
  11152. }
  11153. } else {
  11154. disable( gl.POLYGON_OFFSET_FILL );
  11155. }
  11156. }
  11157. function getScissorTest() {
  11158. return currentScissorTest;
  11159. }
  11160. function setScissorTest( scissorTest ) {
  11161. currentScissorTest = scissorTest;
  11162. if ( scissorTest ) {
  11163. enable( gl.SCISSOR_TEST );
  11164. } else {
  11165. disable( gl.SCISSOR_TEST );
  11166. }
  11167. }
  11168. // texture
  11169. function activeTexture( webglSlot ) {
  11170. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11171. if ( currentTextureSlot !== webglSlot ) {
  11172. gl.activeTexture( webglSlot );
  11173. currentTextureSlot = webglSlot;
  11174. }
  11175. }
  11176. function bindTexture( webglType, webglTexture ) {
  11177. if ( currentTextureSlot === null ) {
  11178. activeTexture();
  11179. }
  11180. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11181. if ( boundTexture === undefined ) {
  11182. boundTexture = { type: undefined, texture: undefined };
  11183. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11184. }
  11185. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11186. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11187. boundTexture.type = webglType;
  11188. boundTexture.texture = webglTexture;
  11189. }
  11190. }
  11191. function compressedTexImage2D() {
  11192. try {
  11193. gl.compressedTexImage2D.apply( gl, arguments );
  11194. } catch ( error ) {
  11195. console.error( error );
  11196. }
  11197. }
  11198. function texImage2D() {
  11199. try {
  11200. gl.texImage2D.apply( gl, arguments );
  11201. } catch ( error ) {
  11202. console.error( error );
  11203. }
  11204. }
  11205. // TODO Deprecate
  11206. function clearColor( r, g, b, a ) {
  11207. colorBuffer.setClear( r, g, b, a );
  11208. }
  11209. function clearDepth( depth ) {
  11210. depthBuffer.setClear( depth );
  11211. }
  11212. function clearStencil( stencil ) {
  11213. stencilBuffer.setClear( stencil );
  11214. }
  11215. //
  11216. function scissor( scissor ) {
  11217. if ( currentScissor.equals( scissor ) === false ) {
  11218. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11219. currentScissor.copy( scissor );
  11220. }
  11221. }
  11222. function viewport( viewport ) {
  11223. if ( currentViewport.equals( viewport ) === false ) {
  11224. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11225. currentViewport.copy( viewport );
  11226. }
  11227. }
  11228. //
  11229. function reset() {
  11230. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11231. if ( enabledAttributes[ i ] === 1 ) {
  11232. gl.disableVertexAttribArray( i );
  11233. enabledAttributes[ i ] = 0;
  11234. }
  11235. }
  11236. capabilities = {};
  11237. compressedTextureFormats = null;
  11238. currentTextureSlot = null;
  11239. currentBoundTextures = {};
  11240. currentBlending = null;
  11241. currentFlipSided = null;
  11242. currentCullFace = null;
  11243. colorBuffer.reset();
  11244. depthBuffer.reset();
  11245. stencilBuffer.reset();
  11246. }
  11247. return {
  11248. buffers: {
  11249. color: colorBuffer,
  11250. depth: depthBuffer,
  11251. stencil: stencilBuffer
  11252. },
  11253. init: init,
  11254. initAttributes: initAttributes,
  11255. enableAttribute: enableAttribute,
  11256. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11257. disableUnusedAttributes: disableUnusedAttributes,
  11258. enable: enable,
  11259. disable: disable,
  11260. getCompressedTextureFormats: getCompressedTextureFormats,
  11261. setBlending: setBlending,
  11262. setColorWrite: setColorWrite,
  11263. setDepthTest: setDepthTest,
  11264. setDepthWrite: setDepthWrite,
  11265. setDepthFunc: setDepthFunc,
  11266. setStencilTest: setStencilTest,
  11267. setStencilWrite: setStencilWrite,
  11268. setStencilFunc: setStencilFunc,
  11269. setStencilOp: setStencilOp,
  11270. setFlipSided: setFlipSided,
  11271. setCullFace: setCullFace,
  11272. setLineWidth: setLineWidth,
  11273. setPolygonOffset: setPolygonOffset,
  11274. getScissorTest: getScissorTest,
  11275. setScissorTest: setScissorTest,
  11276. activeTexture: activeTexture,
  11277. bindTexture: bindTexture,
  11278. compressedTexImage2D: compressedTexImage2D,
  11279. texImage2D: texImage2D,
  11280. clearColor: clearColor,
  11281. clearDepth: clearDepth,
  11282. clearStencil: clearStencil,
  11283. scissor: scissor,
  11284. viewport: viewport,
  11285. reset: reset
  11286. };
  11287. }
  11288. /**
  11289. * @author mrdoob / http://mrdoob.com/
  11290. */
  11291. function WebGLCapabilities( gl, extensions, parameters ) {
  11292. var maxAnisotropy;
  11293. function getMaxAnisotropy() {
  11294. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11295. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11296. if ( extension !== null ) {
  11297. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11298. } else {
  11299. maxAnisotropy = 0;
  11300. }
  11301. return maxAnisotropy;
  11302. }
  11303. function getMaxPrecision( precision ) {
  11304. if ( precision === 'highp' ) {
  11305. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11306. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11307. return 'highp';
  11308. }
  11309. precision = 'mediump';
  11310. }
  11311. if ( precision === 'mediump' ) {
  11312. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11313. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11314. return 'mediump';
  11315. }
  11316. }
  11317. return 'lowp';
  11318. }
  11319. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11320. var maxPrecision = getMaxPrecision( precision );
  11321. if ( maxPrecision !== precision ) {
  11322. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11323. precision = maxPrecision;
  11324. }
  11325. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11326. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11327. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11328. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11329. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11330. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11331. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11332. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11333. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11334. var vertexTextures = maxVertexTextures > 0;
  11335. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11336. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11337. return {
  11338. getMaxAnisotropy: getMaxAnisotropy,
  11339. getMaxPrecision: getMaxPrecision,
  11340. precision: precision,
  11341. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11342. maxTextures: maxTextures,
  11343. maxVertexTextures: maxVertexTextures,
  11344. maxTextureSize: maxTextureSize,
  11345. maxCubemapSize: maxCubemapSize,
  11346. maxAttributes: maxAttributes,
  11347. maxVertexUniforms: maxVertexUniforms,
  11348. maxVaryings: maxVaryings,
  11349. maxFragmentUniforms: maxFragmentUniforms,
  11350. vertexTextures: vertexTextures,
  11351. floatFragmentTextures: floatFragmentTextures,
  11352. floatVertexTextures: floatVertexTextures
  11353. };
  11354. }
  11355. /**
  11356. * @author mrdoob / http://mrdoob.com/
  11357. */
  11358. function WebGLExtensions( gl ) {
  11359. var extensions = {};
  11360. return {
  11361. get: function ( name ) {
  11362. if ( extensions[ name ] !== undefined ) {
  11363. return extensions[ name ];
  11364. }
  11365. var extension;
  11366. switch ( name ) {
  11367. case 'WEBGL_depth_texture':
  11368. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11369. break;
  11370. case 'EXT_texture_filter_anisotropic':
  11371. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11372. break;
  11373. case 'WEBGL_compressed_texture_s3tc':
  11374. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11375. break;
  11376. case 'WEBGL_compressed_texture_pvrtc':
  11377. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11378. break;
  11379. case 'WEBGL_compressed_texture_etc1':
  11380. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11381. break;
  11382. default:
  11383. extension = gl.getExtension( name );
  11384. }
  11385. if ( extension === null ) {
  11386. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11387. }
  11388. extensions[ name ] = extension;
  11389. return extension;
  11390. }
  11391. };
  11392. }
  11393. function WebGLClipping() {
  11394. var scope = this,
  11395. globalState = null,
  11396. numGlobalPlanes = 0,
  11397. localClippingEnabled = false,
  11398. renderingShadows = false,
  11399. plane = new Plane(),
  11400. viewNormalMatrix = new Matrix3(),
  11401. uniform = { value: null, needsUpdate: false };
  11402. this.uniform = uniform;
  11403. this.numPlanes = 0;
  11404. this.init = function( planes, enableLocalClipping, camera ) {
  11405. var enabled =
  11406. planes.length !== 0 ||
  11407. enableLocalClipping ||
  11408. // enable state of previous frame - the clipping code has to
  11409. // run another frame in order to reset the state:
  11410. numGlobalPlanes !== 0 ||
  11411. localClippingEnabled;
  11412. localClippingEnabled = enableLocalClipping;
  11413. globalState = projectPlanes( planes, camera, 0 );
  11414. numGlobalPlanes = planes.length;
  11415. return enabled;
  11416. };
  11417. this.beginShadows = function() {
  11418. renderingShadows = true;
  11419. projectPlanes( null );
  11420. };
  11421. this.endShadows = function() {
  11422. renderingShadows = false;
  11423. resetGlobalState();
  11424. };
  11425. this.setState = function( planes, clipShadows, camera, cache, fromCache ) {
  11426. if ( ! localClippingEnabled ||
  11427. planes === null || planes.length === 0 ||
  11428. renderingShadows && ! clipShadows ) {
  11429. // there's no local clipping
  11430. if ( renderingShadows ) {
  11431. // there's no global clipping
  11432. projectPlanes( null );
  11433. } else {
  11434. resetGlobalState();
  11435. }
  11436. } else {
  11437. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11438. lGlobal = nGlobal * 4,
  11439. dstArray = cache.clippingState || null;
  11440. uniform.value = dstArray; // ensure unique state
  11441. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11442. for ( var i = 0; i !== lGlobal; ++ i ) {
  11443. dstArray[ i ] = globalState[ i ];
  11444. }
  11445. cache.clippingState = dstArray;
  11446. this.numPlanes += nGlobal;
  11447. }
  11448. };
  11449. function resetGlobalState() {
  11450. if ( uniform.value !== globalState ) {
  11451. uniform.value = globalState;
  11452. uniform.needsUpdate = numGlobalPlanes > 0;
  11453. }
  11454. scope.numPlanes = numGlobalPlanes;
  11455. }
  11456. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11457. var nPlanes = planes !== null ? planes.length : 0,
  11458. dstArray = null;
  11459. if ( nPlanes !== 0 ) {
  11460. dstArray = uniform.value;
  11461. if ( skipTransform !== true || dstArray === null ) {
  11462. var flatSize = dstOffset + nPlanes * 4,
  11463. viewMatrix = camera.matrixWorldInverse;
  11464. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11465. if ( dstArray === null || dstArray.length < flatSize ) {
  11466. dstArray = new Float32Array( flatSize );
  11467. }
  11468. for ( var i = 0, i4 = dstOffset;
  11469. i !== nPlanes; ++ i, i4 += 4 ) {
  11470. plane.copy( planes[ i ] ).
  11471. applyMatrix4( viewMatrix, viewNormalMatrix );
  11472. plane.normal.toArray( dstArray, i4 );
  11473. dstArray[ i4 + 3 ] = plane.constant;
  11474. }
  11475. }
  11476. uniform.value = dstArray;
  11477. uniform.needsUpdate = true;
  11478. }
  11479. scope.numPlanes = nPlanes;
  11480. return dstArray;
  11481. }
  11482. }
  11483. /**
  11484. * @author supereggbert / http://www.paulbrunt.co.uk/
  11485. * @author mrdoob / http://mrdoob.com/
  11486. * @author alteredq / http://alteredqualia.com/
  11487. * @author szimek / https://github.com/szimek/
  11488. * @author tschw
  11489. */
  11490. function WebGLRenderer( parameters ) {
  11491. console.log( 'THREE.WebGLRenderer', REVISION );
  11492. parameters = parameters || {};
  11493. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11494. _context = parameters.context !== undefined ? parameters.context : null,
  11495. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11496. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11497. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11498. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11499. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11500. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11501. var lights = [];
  11502. var opaqueObjects = [];
  11503. var opaqueObjectsLastIndex = - 1;
  11504. var transparentObjects = [];
  11505. var transparentObjectsLastIndex = - 1;
  11506. var morphInfluences = new Float32Array( 8 );
  11507. var sprites = [];
  11508. var lensFlares = [];
  11509. // public properties
  11510. this.domElement = _canvas;
  11511. this.context = null;
  11512. // clearing
  11513. this.autoClear = true;
  11514. this.autoClearColor = true;
  11515. this.autoClearDepth = true;
  11516. this.autoClearStencil = true;
  11517. // scene graph
  11518. this.sortObjects = true;
  11519. // user-defined clipping
  11520. this.clippingPlanes = [];
  11521. this.localClippingEnabled = false;
  11522. // physically based shading
  11523. this.gammaFactor = 2.0; // for backwards compatibility
  11524. this.gammaInput = false;
  11525. this.gammaOutput = false;
  11526. // physical lights
  11527. this.physicallyCorrectLights = false;
  11528. // tone mapping
  11529. this.toneMapping = LinearToneMapping;
  11530. this.toneMappingExposure = 1.0;
  11531. this.toneMappingWhitePoint = 1.0;
  11532. // morphs
  11533. this.maxMorphTargets = 8;
  11534. this.maxMorphNormals = 4;
  11535. // internal properties
  11536. var _this = this,
  11537. // internal state cache
  11538. _currentProgram = null,
  11539. _currentRenderTarget = null,
  11540. _currentFramebuffer = null,
  11541. _currentMaterialId = - 1,
  11542. _currentGeometryProgram = '',
  11543. _currentCamera = null,
  11544. _currentScissor = new Vector4(),
  11545. _currentScissorTest = null,
  11546. _currentViewport = new Vector4(),
  11547. //
  11548. _usedTextureUnits = 0,
  11549. //
  11550. _clearColor = new Color( 0x000000 ),
  11551. _clearAlpha = 0,
  11552. _width = _canvas.width,
  11553. _height = _canvas.height,
  11554. _pixelRatio = 1,
  11555. _scissor = new Vector4( 0, 0, _width, _height ),
  11556. _scissorTest = false,
  11557. _viewport = new Vector4( 0, 0, _width, _height ),
  11558. // frustum
  11559. _frustum = new Frustum(),
  11560. // clipping
  11561. _clipping = new WebGLClipping(),
  11562. _clippingEnabled = false,
  11563. _localClippingEnabled = false,
  11564. _sphere = new Sphere(),
  11565. // camera matrices cache
  11566. _projScreenMatrix = new Matrix4(),
  11567. _vector3 = new Vector3(),
  11568. // light arrays cache
  11569. _lights = {
  11570. hash: '',
  11571. ambient: [ 0, 0, 0 ],
  11572. directional: [],
  11573. directionalShadowMap: [],
  11574. directionalShadowMatrix: [],
  11575. spot: [],
  11576. spotShadowMap: [],
  11577. spotShadowMatrix: [],
  11578. point: [],
  11579. pointShadowMap: [],
  11580. pointShadowMatrix: [],
  11581. hemi: [],
  11582. shadows: []
  11583. },
  11584. // info
  11585. _infoRender = {
  11586. calls: 0,
  11587. vertices: 0,
  11588. faces: 0,
  11589. points: 0
  11590. };
  11591. this.info = {
  11592. render: _infoRender,
  11593. memory: {
  11594. geometries: 0,
  11595. textures: 0
  11596. },
  11597. programs: null
  11598. };
  11599. // initialize
  11600. var _gl;
  11601. try {
  11602. var attributes = {
  11603. alpha: _alpha,
  11604. depth: _depth,
  11605. stencil: _stencil,
  11606. antialias: _antialias,
  11607. premultipliedAlpha: _premultipliedAlpha,
  11608. preserveDrawingBuffer: _preserveDrawingBuffer
  11609. };
  11610. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11611. if ( _gl === null ) {
  11612. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11613. throw 'Error creating WebGL context with your selected attributes.';
  11614. } else {
  11615. throw 'Error creating WebGL context.';
  11616. }
  11617. }
  11618. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11619. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11620. _gl.getShaderPrecisionFormat = function () {
  11621. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11622. };
  11623. }
  11624. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11625. } catch ( error ) {
  11626. console.error( 'THREE.WebGLRenderer: ' + error );
  11627. }
  11628. var extensions = new WebGLExtensions( _gl );
  11629. extensions.get( 'WEBGL_depth_texture' );
  11630. extensions.get( 'OES_texture_float' );
  11631. extensions.get( 'OES_texture_float_linear' );
  11632. extensions.get( 'OES_texture_half_float' );
  11633. extensions.get( 'OES_texture_half_float_linear' );
  11634. extensions.get( 'OES_standard_derivatives' );
  11635. extensions.get( 'ANGLE_instanced_arrays' );
  11636. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11637. BufferGeometry.MaxIndex = 4294967296;
  11638. }
  11639. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11640. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11641. var properties = new WebGLProperties();
  11642. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11643. var objects = new WebGLObjects( _gl, properties, this.info );
  11644. var programCache = new WebGLPrograms( this, capabilities );
  11645. var lightCache = new WebGLLights();
  11646. this.info.programs = programCache.programs;
  11647. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11648. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11649. //
  11650. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11651. var backgroundCamera2 = new PerspectiveCamera();
  11652. var backgroundPlaneMesh = new Mesh(
  11653. new PlaneBufferGeometry( 2, 2 ),
  11654. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11655. );
  11656. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11657. var backgroundBoxMesh = new Mesh(
  11658. new BoxBufferGeometry( 5, 5, 5 ),
  11659. new ShaderMaterial( {
  11660. uniforms: backgroundBoxShader.uniforms,
  11661. vertexShader: backgroundBoxShader.vertexShader,
  11662. fragmentShader: backgroundBoxShader.fragmentShader,
  11663. side: BackSide,
  11664. depthTest: false,
  11665. depthWrite: false,
  11666. fog: false
  11667. } )
  11668. );
  11669. //
  11670. function getTargetPixelRatio() {
  11671. return _currentRenderTarget === null ? _pixelRatio : 1;
  11672. }
  11673. function glClearColor( r, g, b, a ) {
  11674. if ( _premultipliedAlpha === true ) {
  11675. r *= a; g *= a; b *= a;
  11676. }
  11677. state.clearColor( r, g, b, a );
  11678. }
  11679. function setDefaultGLState() {
  11680. state.init();
  11681. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11682. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11683. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11684. }
  11685. function resetGLState() {
  11686. _currentProgram = null;
  11687. _currentCamera = null;
  11688. _currentGeometryProgram = '';
  11689. _currentMaterialId = - 1;
  11690. state.reset();
  11691. }
  11692. setDefaultGLState();
  11693. this.context = _gl;
  11694. this.capabilities = capabilities;
  11695. this.extensions = extensions;
  11696. this.properties = properties;
  11697. this.state = state;
  11698. // shadow map
  11699. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11700. this.shadowMap = shadowMap;
  11701. // Plugins
  11702. var spritePlugin = new SpritePlugin( this, sprites );
  11703. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11704. // API
  11705. this.getContext = function () {
  11706. return _gl;
  11707. };
  11708. this.getContextAttributes = function () {
  11709. return _gl.getContextAttributes();
  11710. };
  11711. this.forceContextLoss = function () {
  11712. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11713. };
  11714. this.getMaxAnisotropy = function () {
  11715. return capabilities.getMaxAnisotropy();
  11716. };
  11717. this.getPrecision = function () {
  11718. return capabilities.precision;
  11719. };
  11720. this.getPixelRatio = function () {
  11721. return _pixelRatio;
  11722. };
  11723. this.setPixelRatio = function ( value ) {
  11724. if ( value === undefined ) return;
  11725. _pixelRatio = value;
  11726. this.setSize( _viewport.z, _viewport.w, false );
  11727. };
  11728. this.getSize = function () {
  11729. return {
  11730. width: _width,
  11731. height: _height
  11732. };
  11733. };
  11734. this.setSize = function ( width, height, updateStyle ) {
  11735. _width = width;
  11736. _height = height;
  11737. _canvas.width = width * _pixelRatio;
  11738. _canvas.height = height * _pixelRatio;
  11739. if ( updateStyle !== false ) {
  11740. _canvas.style.width = width + 'px';
  11741. _canvas.style.height = height + 'px';
  11742. }
  11743. this.setViewport( 0, 0, width, height );
  11744. };
  11745. this.setViewport = function ( x, y, width, height ) {
  11746. state.viewport( _viewport.set( x, y, width, height ) );
  11747. };
  11748. this.setScissor = function ( x, y, width, height ) {
  11749. state.scissor( _scissor.set( x, y, width, height ) );
  11750. };
  11751. this.setScissorTest = function ( boolean ) {
  11752. state.setScissorTest( _scissorTest = boolean );
  11753. };
  11754. // Clearing
  11755. this.getClearColor = function () {
  11756. return _clearColor;
  11757. };
  11758. this.setClearColor = function ( color, alpha ) {
  11759. _clearColor.set( color );
  11760. _clearAlpha = alpha !== undefined ? alpha : 1;
  11761. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11762. };
  11763. this.getClearAlpha = function () {
  11764. return _clearAlpha;
  11765. };
  11766. this.setClearAlpha = function ( alpha ) {
  11767. _clearAlpha = alpha;
  11768. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11769. };
  11770. this.clear = function ( color, depth, stencil ) {
  11771. var bits = 0;
  11772. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11773. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11774. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11775. _gl.clear( bits );
  11776. };
  11777. this.clearColor = function () {
  11778. this.clear( true, false, false );
  11779. };
  11780. this.clearDepth = function () {
  11781. this.clear( false, true, false );
  11782. };
  11783. this.clearStencil = function () {
  11784. this.clear( false, false, true );
  11785. };
  11786. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11787. this.setRenderTarget( renderTarget );
  11788. this.clear( color, depth, stencil );
  11789. };
  11790. // Reset
  11791. this.resetGLState = resetGLState;
  11792. this.dispose = function() {
  11793. transparentObjects = [];
  11794. transparentObjectsLastIndex = -1;
  11795. opaqueObjects = [];
  11796. opaqueObjectsLastIndex = -1;
  11797. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11798. };
  11799. // Events
  11800. function onContextLost( event ) {
  11801. event.preventDefault();
  11802. resetGLState();
  11803. setDefaultGLState();
  11804. properties.clear();
  11805. }
  11806. function onMaterialDispose( event ) {
  11807. var material = event.target;
  11808. material.removeEventListener( 'dispose', onMaterialDispose );
  11809. deallocateMaterial( material );
  11810. }
  11811. // Buffer deallocation
  11812. function deallocateMaterial( material ) {
  11813. releaseMaterialProgramReference( material );
  11814. properties.delete( material );
  11815. }
  11816. function releaseMaterialProgramReference( material ) {
  11817. var programInfo = properties.get( material ).program;
  11818. material.program = undefined;
  11819. if ( programInfo !== undefined ) {
  11820. programCache.releaseProgram( programInfo );
  11821. }
  11822. }
  11823. // Buffer rendering
  11824. this.renderBufferImmediate = function ( object, program, material ) {
  11825. state.initAttributes();
  11826. var buffers = properties.get( object );
  11827. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11828. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11829. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11830. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11831. var attributes = program.getAttributes();
  11832. if ( object.hasPositions ) {
  11833. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11834. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11835. state.enableAttribute( attributes.position );
  11836. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11837. }
  11838. if ( object.hasNormals ) {
  11839. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  11840. if ( ! material.isMeshPhongMaterial &&
  11841. ! material.isMeshStandardMaterial &&
  11842. material.shading === FlatShading ) {
  11843. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  11844. var array = object.normalArray;
  11845. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  11846. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  11847. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  11848. array[ i + 0 ] = nx;
  11849. array[ i + 1 ] = ny;
  11850. array[ i + 2 ] = nz;
  11851. array[ i + 3 ] = nx;
  11852. array[ i + 4 ] = ny;
  11853. array[ i + 5 ] = nz;
  11854. array[ i + 6 ] = nx;
  11855. array[ i + 7 ] = ny;
  11856. array[ i + 8 ] = nz;
  11857. }
  11858. }
  11859. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11860. state.enableAttribute( attributes.normal );
  11861. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11862. }
  11863. if ( object.hasUvs && material.map ) {
  11864. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  11865. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11866. state.enableAttribute( attributes.uv );
  11867. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11868. }
  11869. if ( object.hasColors && material.vertexColors !== NoColors ) {
  11870. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  11871. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11872. state.enableAttribute( attributes.color );
  11873. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11874. }
  11875. state.disableUnusedAttributes();
  11876. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11877. object.count = 0;
  11878. };
  11879. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  11880. setMaterial( material );
  11881. var program = setProgram( camera, fog, material, object );
  11882. var updateBuffers = false;
  11883. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  11884. if ( geometryProgram !== _currentGeometryProgram ) {
  11885. _currentGeometryProgram = geometryProgram;
  11886. updateBuffers = true;
  11887. }
  11888. // morph targets
  11889. var morphTargetInfluences = object.morphTargetInfluences;
  11890. if ( morphTargetInfluences !== undefined ) {
  11891. var activeInfluences = [];
  11892. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  11893. var influence = morphTargetInfluences[ i ];
  11894. activeInfluences.push( [ influence, i ] );
  11895. }
  11896. activeInfluences.sort( absNumericalSort );
  11897. if ( activeInfluences.length > 8 ) {
  11898. activeInfluences.length = 8;
  11899. }
  11900. var morphAttributes = geometry.morphAttributes;
  11901. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  11902. var influence = activeInfluences[ i ];
  11903. morphInfluences[ i ] = influence[ 0 ];
  11904. if ( influence[ 0 ] !== 0 ) {
  11905. var index = influence[ 1 ];
  11906. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  11907. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  11908. } else {
  11909. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  11910. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  11911. }
  11912. }
  11913. program.getUniforms().setValue(
  11914. _gl, 'morphTargetInfluences', morphInfluences );
  11915. updateBuffers = true;
  11916. }
  11917. //
  11918. var index = geometry.index;
  11919. var position = geometry.attributes.position;
  11920. if ( material.wireframe === true ) {
  11921. index = objects.getWireframeAttribute( geometry );
  11922. }
  11923. var renderer;
  11924. if ( index !== null ) {
  11925. renderer = indexedBufferRenderer;
  11926. renderer.setIndex( index );
  11927. } else {
  11928. renderer = bufferRenderer;
  11929. }
  11930. if ( updateBuffers ) {
  11931. setupVertexAttributes( material, program, geometry );
  11932. if ( index !== null ) {
  11933. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  11934. }
  11935. }
  11936. //
  11937. var dataStart = 0;
  11938. var dataCount = Infinity;
  11939. if ( index !== null ) {
  11940. dataCount = index.count;
  11941. } else if ( position !== undefined ) {
  11942. dataCount = position.count;
  11943. }
  11944. var rangeStart = geometry.drawRange.start;
  11945. var rangeCount = geometry.drawRange.count;
  11946. var groupStart = group !== null ? group.start : 0;
  11947. var groupCount = group !== null ? group.count : Infinity;
  11948. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  11949. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  11950. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  11951. //
  11952. if ( object.isMesh ) {
  11953. if ( material.wireframe === true ) {
  11954. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  11955. renderer.setMode( _gl.LINES );
  11956. } else {
  11957. switch ( object.drawMode ) {
  11958. case TrianglesDrawMode:
  11959. renderer.setMode( _gl.TRIANGLES );
  11960. break;
  11961. case TriangleStripDrawMode:
  11962. renderer.setMode( _gl.TRIANGLE_STRIP );
  11963. break;
  11964. case TriangleFanDrawMode:
  11965. renderer.setMode( _gl.TRIANGLE_FAN );
  11966. break;
  11967. }
  11968. }
  11969. } else if ( object.isLine ) {
  11970. var lineWidth = material.linewidth;
  11971. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  11972. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  11973. if ( object.isLineSegments ) {
  11974. renderer.setMode( _gl.LINES );
  11975. } else {
  11976. renderer.setMode( _gl.LINE_STRIP );
  11977. }
  11978. } else if ( object.isPoints ) {
  11979. renderer.setMode( _gl.POINTS );
  11980. }
  11981. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11982. if ( geometry.maxInstancedCount > 0 ) {
  11983. renderer.renderInstances( geometry, drawStart, drawCount );
  11984. }
  11985. } else {
  11986. renderer.render( drawStart, drawCount );
  11987. }
  11988. };
  11989. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11990. var extension;
  11991. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11992. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11993. if ( extension === null ) {
  11994. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11995. return;
  11996. }
  11997. }
  11998. if ( startIndex === undefined ) startIndex = 0;
  11999. state.initAttributes();
  12000. var geometryAttributes = geometry.attributes;
  12001. var programAttributes = program.getAttributes();
  12002. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12003. for ( var name in programAttributes ) {
  12004. var programAttribute = programAttributes[ name ];
  12005. if ( programAttribute >= 0 ) {
  12006. var geometryAttribute = geometryAttributes[ name ];
  12007. if ( geometryAttribute !== undefined ) {
  12008. var type = _gl.FLOAT;
  12009. var array = geometryAttribute.array;
  12010. var normalized = geometryAttribute.normalized;
  12011. if ( array instanceof Float32Array ) {
  12012. type = _gl.FLOAT;
  12013. } else if ( array instanceof Float64Array ) {
  12014. console.warn( "Unsupported data buffer format: Float64Array" );
  12015. } else if ( array instanceof Uint16Array ) {
  12016. type = _gl.UNSIGNED_SHORT;
  12017. } else if ( array instanceof Int16Array ) {
  12018. type = _gl.SHORT;
  12019. } else if ( array instanceof Uint32Array ) {
  12020. type = _gl.UNSIGNED_INT;
  12021. } else if ( array instanceof Int32Array ) {
  12022. type = _gl.INT;
  12023. } else if ( array instanceof Int8Array ) {
  12024. type = _gl.BYTE;
  12025. } else if ( array instanceof Uint8Array ) {
  12026. type = _gl.UNSIGNED_BYTE;
  12027. }
  12028. var size = geometryAttribute.itemSize;
  12029. var buffer = objects.getAttributeBuffer( geometryAttribute );
  12030. if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) {
  12031. var data = geometryAttribute.data;
  12032. var stride = data.stride;
  12033. var offset = geometryAttribute.offset;
  12034. if ( data && data.isInstancedInterleavedBuffer ) {
  12035. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12036. if ( geometry.maxInstancedCount === undefined ) {
  12037. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12038. }
  12039. } else {
  12040. state.enableAttribute( programAttribute );
  12041. }
  12042. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12043. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  12044. } else {
  12045. if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) {
  12046. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12047. if ( geometry.maxInstancedCount === undefined ) {
  12048. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12049. }
  12050. } else {
  12051. state.enableAttribute( programAttribute );
  12052. }
  12053. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12054. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  12055. }
  12056. } else if ( materialDefaultAttributeValues !== undefined ) {
  12057. var value = materialDefaultAttributeValues[ name ];
  12058. if ( value !== undefined ) {
  12059. switch ( value.length ) {
  12060. case 2:
  12061. _gl.vertexAttrib2fv( programAttribute, value );
  12062. break;
  12063. case 3:
  12064. _gl.vertexAttrib3fv( programAttribute, value );
  12065. break;
  12066. case 4:
  12067. _gl.vertexAttrib4fv( programAttribute, value );
  12068. break;
  12069. default:
  12070. _gl.vertexAttrib1fv( programAttribute, value );
  12071. }
  12072. }
  12073. }
  12074. }
  12075. }
  12076. state.disableUnusedAttributes();
  12077. }
  12078. // Sorting
  12079. function absNumericalSort( a, b ) {
  12080. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12081. }
  12082. function painterSortStable( a, b ) {
  12083. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12084. return a.object.renderOrder - b.object.renderOrder;
  12085. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12086. return a.material.program.id - b.material.program.id;
  12087. } else if ( a.material.id !== b.material.id ) {
  12088. return a.material.id - b.material.id;
  12089. } else if ( a.z !== b.z ) {
  12090. return a.z - b.z;
  12091. } else {
  12092. return a.id - b.id;
  12093. }
  12094. }
  12095. function reversePainterSortStable( a, b ) {
  12096. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12097. return a.object.renderOrder - b.object.renderOrder;
  12098. } if ( a.z !== b.z ) {
  12099. return b.z - a.z;
  12100. } else {
  12101. return a.id - b.id;
  12102. }
  12103. }
  12104. // Rendering
  12105. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12106. if ( ( camera && camera.isCamera ) === false ) {
  12107. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12108. return;
  12109. }
  12110. var fog = scene.fog;
  12111. // reset caching for this frame
  12112. _currentGeometryProgram = '';
  12113. _currentMaterialId = - 1;
  12114. _currentCamera = null;
  12115. // update scene graph
  12116. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12117. // update camera matrices and frustum
  12118. if ( camera.parent === null ) camera.updateMatrixWorld();
  12119. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12120. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12121. _frustum.setFromMatrix( _projScreenMatrix );
  12122. lights.length = 0;
  12123. opaqueObjectsLastIndex = - 1;
  12124. transparentObjectsLastIndex = - 1;
  12125. sprites.length = 0;
  12126. lensFlares.length = 0;
  12127. _localClippingEnabled = this.localClippingEnabled;
  12128. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12129. projectObject( scene, camera );
  12130. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12131. transparentObjects.length = transparentObjectsLastIndex + 1;
  12132. if ( _this.sortObjects === true ) {
  12133. opaqueObjects.sort( painterSortStable );
  12134. transparentObjects.sort( reversePainterSortStable );
  12135. }
  12136. //
  12137. if ( _clippingEnabled ) _clipping.beginShadows();
  12138. setupShadows( lights );
  12139. shadowMap.render( scene, camera );
  12140. setupLights( lights, camera );
  12141. if ( _clippingEnabled ) _clipping.endShadows();
  12142. //
  12143. _infoRender.calls = 0;
  12144. _infoRender.vertices = 0;
  12145. _infoRender.faces = 0;
  12146. _infoRender.points = 0;
  12147. if ( renderTarget === undefined ) {
  12148. renderTarget = null;
  12149. }
  12150. this.setRenderTarget( renderTarget );
  12151. //
  12152. var background = scene.background;
  12153. if ( background === null ) {
  12154. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12155. } else if ( background && background.isColor ) {
  12156. glClearColor( background.r, background.g, background.b, 1 );
  12157. forceClear = true;
  12158. }
  12159. if ( this.autoClear || forceClear ) {
  12160. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12161. }
  12162. if ( background && background.isCubeTexture ) {
  12163. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12164. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12165. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12166. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12167. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12168. objects.update( backgroundBoxMesh );
  12169. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12170. } else if ( background && background.isTexture ) {
  12171. backgroundPlaneMesh.material.map = background;
  12172. objects.update( backgroundPlaneMesh );
  12173. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12174. }
  12175. //
  12176. if ( scene.overrideMaterial ) {
  12177. var overrideMaterial = scene.overrideMaterial;
  12178. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  12179. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  12180. } else {
  12181. // opaque pass (front-to-back order)
  12182. state.setBlending( NoBlending );
  12183. renderObjects( opaqueObjects, camera, fog );
  12184. // transparent pass (back-to-front order)
  12185. renderObjects( transparentObjects, camera, fog );
  12186. }
  12187. // custom render plugins (post pass)
  12188. spritePlugin.render( scene, camera );
  12189. lensFlarePlugin.render( scene, camera, _currentViewport );
  12190. // Generate mipmap if we're using any kind of mipmap filtering
  12191. if ( renderTarget ) {
  12192. textures.updateRenderTargetMipmap( renderTarget );
  12193. }
  12194. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12195. state.setDepthTest( true );
  12196. state.setDepthWrite( true );
  12197. state.setColorWrite( true );
  12198. // _gl.finish();
  12199. };
  12200. function pushRenderItem( object, geometry, material, z, group ) {
  12201. var array, index;
  12202. // allocate the next position in the appropriate array
  12203. if ( material.transparent ) {
  12204. array = transparentObjects;
  12205. index = ++ transparentObjectsLastIndex;
  12206. } else {
  12207. array = opaqueObjects;
  12208. index = ++ opaqueObjectsLastIndex;
  12209. }
  12210. // recycle existing render item or grow the array
  12211. var renderItem = array[ index ];
  12212. if ( renderItem !== undefined ) {
  12213. renderItem.id = object.id;
  12214. renderItem.object = object;
  12215. renderItem.geometry = geometry;
  12216. renderItem.material = material;
  12217. renderItem.z = _vector3.z;
  12218. renderItem.group = group;
  12219. } else {
  12220. renderItem = {
  12221. id: object.id,
  12222. object: object,
  12223. geometry: geometry,
  12224. material: material,
  12225. z: _vector3.z,
  12226. group: group
  12227. };
  12228. // assert( index === array.length );
  12229. array.push( renderItem );
  12230. }
  12231. }
  12232. // TODO Duplicated code (Frustum)
  12233. function isObjectViewable( object ) {
  12234. var geometry = object.geometry;
  12235. if ( geometry.boundingSphere === null )
  12236. geometry.computeBoundingSphere();
  12237. _sphere.copy( geometry.boundingSphere ).
  12238. applyMatrix4( object.matrixWorld );
  12239. return isSphereViewable( _sphere );
  12240. }
  12241. function isSpriteViewable( sprite ) {
  12242. _sphere.center.set( 0, 0, 0 );
  12243. _sphere.radius = 0.7071067811865476;
  12244. _sphere.applyMatrix4( sprite.matrixWorld );
  12245. return isSphereViewable( _sphere );
  12246. }
  12247. function isSphereViewable( sphere ) {
  12248. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12249. var numPlanes = _clipping.numPlanes;
  12250. if ( numPlanes === 0 ) return true;
  12251. var planes = _this.clippingPlanes,
  12252. center = sphere.center,
  12253. negRad = - sphere.radius,
  12254. i = 0;
  12255. do {
  12256. // out when deeper than radius in the negative halfspace
  12257. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12258. } while ( ++ i !== numPlanes );
  12259. return true;
  12260. }
  12261. function projectObject( object, camera ) {
  12262. if ( object.visible === false ) return;
  12263. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12264. if ( visible ) {
  12265. if ( object.isLight ) {
  12266. lights.push( object );
  12267. } else if ( object.isSprite ) {
  12268. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12269. sprites.push( object );
  12270. }
  12271. } else if ( object.isLensFlare ) {
  12272. lensFlares.push( object );
  12273. } else if ( object.isImmediateRenderObject ) {
  12274. if ( _this.sortObjects === true ) {
  12275. _vector3.setFromMatrixPosition( object.matrixWorld );
  12276. _vector3.applyProjection( _projScreenMatrix );
  12277. }
  12278. pushRenderItem( object, null, object.material, _vector3.z, null );
  12279. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12280. if ( object.isSkinnedMesh ) {
  12281. object.skeleton.update();
  12282. }
  12283. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12284. var material = object.material;
  12285. if ( material.visible === true ) {
  12286. if ( _this.sortObjects === true ) {
  12287. _vector3.setFromMatrixPosition( object.matrixWorld );
  12288. _vector3.applyProjection( _projScreenMatrix );
  12289. }
  12290. var geometry = objects.update( object );
  12291. if ( material.isMultiMaterial ) {
  12292. var groups = geometry.groups;
  12293. var materials = material.materials;
  12294. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12295. var group = groups[ i ];
  12296. var groupMaterial = materials[ group.materialIndex ];
  12297. if ( groupMaterial.visible === true ) {
  12298. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12299. }
  12300. }
  12301. } else {
  12302. pushRenderItem( object, geometry, material, _vector3.z, null );
  12303. }
  12304. }
  12305. }
  12306. }
  12307. }
  12308. var children = object.children;
  12309. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12310. projectObject( children[ i ], camera );
  12311. }
  12312. }
  12313. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  12314. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12315. var renderItem = renderList[ i ];
  12316. var object = renderItem.object;
  12317. var geometry = renderItem.geometry;
  12318. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12319. var group = renderItem.group;
  12320. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12321. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12322. if ( object.isImmediateRenderObject ) {
  12323. setMaterial( material );
  12324. var program = setProgram( camera, fog, material, object );
  12325. _currentGeometryProgram = '';
  12326. object.render( function ( object ) {
  12327. _this.renderBufferImmediate( object, program, material );
  12328. } );
  12329. } else {
  12330. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  12331. }
  12332. }
  12333. }
  12334. function initMaterial( material, fog, object ) {
  12335. var materialProperties = properties.get( material );
  12336. var parameters = programCache.getParameters(
  12337. material, _lights, fog, _clipping.numPlanes, object );
  12338. var code = programCache.getProgramCode( material, parameters );
  12339. var program = materialProperties.program;
  12340. var programChange = true;
  12341. if ( program === undefined ) {
  12342. // new material
  12343. material.addEventListener( 'dispose', onMaterialDispose );
  12344. } else if ( program.code !== code ) {
  12345. // changed glsl or parameters
  12346. releaseMaterialProgramReference( material );
  12347. } else if ( parameters.shaderID !== undefined ) {
  12348. // same glsl and uniform list
  12349. return;
  12350. } else {
  12351. // only rebuild uniform list
  12352. programChange = false;
  12353. }
  12354. if ( programChange ) {
  12355. if ( parameters.shaderID ) {
  12356. var shader = ShaderLib[ parameters.shaderID ];
  12357. materialProperties.__webglShader = {
  12358. name: material.type,
  12359. uniforms: exports.UniformsUtils.clone( shader.uniforms ),
  12360. vertexShader: shader.vertexShader,
  12361. fragmentShader: shader.fragmentShader
  12362. };
  12363. } else {
  12364. materialProperties.__webglShader = {
  12365. name: material.type,
  12366. uniforms: material.uniforms,
  12367. vertexShader: material.vertexShader,
  12368. fragmentShader: material.fragmentShader
  12369. };
  12370. }
  12371. material.__webglShader = materialProperties.__webglShader;
  12372. program = programCache.acquireProgram( material, parameters, code );
  12373. materialProperties.program = program;
  12374. material.program = program;
  12375. }
  12376. var attributes = program.getAttributes();
  12377. if ( material.morphTargets ) {
  12378. material.numSupportedMorphTargets = 0;
  12379. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12380. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12381. material.numSupportedMorphTargets ++;
  12382. }
  12383. }
  12384. }
  12385. if ( material.morphNormals ) {
  12386. material.numSupportedMorphNormals = 0;
  12387. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12388. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12389. material.numSupportedMorphNormals ++;
  12390. }
  12391. }
  12392. }
  12393. var uniforms = materialProperties.__webglShader.uniforms;
  12394. if ( ! material.isShaderMaterial &&
  12395. ! material.isRawShaderMaterial ||
  12396. material.clipping === true ) {
  12397. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12398. uniforms.clippingPlanes = _clipping.uniform;
  12399. }
  12400. materialProperties.fog = fog;
  12401. // store the light setup it was created for
  12402. materialProperties.lightsHash = _lights.hash;
  12403. if ( material.lights ) {
  12404. // wire up the material to this renderer's lighting state
  12405. uniforms.ambientLightColor.value = _lights.ambient;
  12406. uniforms.directionalLights.value = _lights.directional;
  12407. uniforms.spotLights.value = _lights.spot;
  12408. uniforms.pointLights.value = _lights.point;
  12409. uniforms.hemisphereLights.value = _lights.hemi;
  12410. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12411. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12412. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12413. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12414. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12415. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12416. }
  12417. var progUniforms = materialProperties.program.getUniforms(),
  12418. uniformsList =
  12419. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12420. materialProperties.uniformsList = uniformsList;
  12421. materialProperties.dynamicUniforms =
  12422. WebGLUniforms.splitDynamic( uniformsList, uniforms );
  12423. }
  12424. function setMaterial( material ) {
  12425. material.side === DoubleSide
  12426. ? state.disable( _gl.CULL_FACE )
  12427. : state.enable( _gl.CULL_FACE );
  12428. state.setFlipSided( material.side === BackSide );
  12429. material.transparent === true
  12430. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12431. : state.setBlending( NoBlending );
  12432. state.setDepthFunc( material.depthFunc );
  12433. state.setDepthTest( material.depthTest );
  12434. state.setDepthWrite( material.depthWrite );
  12435. state.setColorWrite( material.colorWrite );
  12436. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12437. }
  12438. function setProgram( camera, fog, material, object ) {
  12439. _usedTextureUnits = 0;
  12440. var materialProperties = properties.get( material );
  12441. if ( _clippingEnabled ) {
  12442. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12443. var useCache =
  12444. camera === _currentCamera &&
  12445. material.id === _currentMaterialId;
  12446. // we might want to call this function with some ClippingGroup
  12447. // object instead of the material, once it becomes feasible
  12448. // (#8465, #8379)
  12449. _clipping.setState(
  12450. material.clippingPlanes, material.clipShadows,
  12451. camera, materialProperties, useCache );
  12452. }
  12453. }
  12454. if ( material.needsUpdate === false ) {
  12455. if ( materialProperties.program === undefined ) {
  12456. material.needsUpdate = true;
  12457. } else if ( material.fog && materialProperties.fog !== fog ) {
  12458. material.needsUpdate = true;
  12459. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12460. material.needsUpdate = true;
  12461. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12462. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  12463. material.needsUpdate = true;
  12464. }
  12465. }
  12466. if ( material.needsUpdate ) {
  12467. initMaterial( material, fog, object );
  12468. material.needsUpdate = false;
  12469. }
  12470. var refreshProgram = false;
  12471. var refreshMaterial = false;
  12472. var refreshLights = false;
  12473. var program = materialProperties.program,
  12474. p_uniforms = program.getUniforms(),
  12475. m_uniforms = materialProperties.__webglShader.uniforms;
  12476. if ( program.id !== _currentProgram ) {
  12477. _gl.useProgram( program.program );
  12478. _currentProgram = program.id;
  12479. refreshProgram = true;
  12480. refreshMaterial = true;
  12481. refreshLights = true;
  12482. }
  12483. if ( material.id !== _currentMaterialId ) {
  12484. _currentMaterialId = material.id;
  12485. refreshMaterial = true;
  12486. }
  12487. if ( refreshProgram || camera !== _currentCamera ) {
  12488. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12489. if ( capabilities.logarithmicDepthBuffer ) {
  12490. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12491. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12492. }
  12493. if ( camera !== _currentCamera ) {
  12494. _currentCamera = camera;
  12495. // lighting uniforms depend on the camera so enforce an update
  12496. // now, in case this material supports lights - or later, when
  12497. // the next material that does gets activated:
  12498. refreshMaterial = true; // set to true on material change
  12499. refreshLights = true; // remains set until update done
  12500. }
  12501. // load material specific uniforms
  12502. // (shader material also gets them for the sake of genericity)
  12503. if ( material.isShaderMaterial ||
  12504. material.isMeshPhongMaterial ||
  12505. material.isMeshStandardMaterial ||
  12506. material.envMap ) {
  12507. var uCamPos = p_uniforms.map.cameraPosition;
  12508. if ( uCamPos !== undefined ) {
  12509. uCamPos.setValue( _gl,
  12510. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12511. }
  12512. }
  12513. if ( material.isMeshPhongMaterial ||
  12514. material.isMeshLambertMaterial ||
  12515. material.isMeshBasicMaterial ||
  12516. material.isMeshStandardMaterial ||
  12517. material.isShaderMaterial ||
  12518. material.skinning ) {
  12519. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12520. }
  12521. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12522. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12523. }
  12524. // skinning uniforms must be set even if material didn't change
  12525. // auto-setting of texture unit for bone texture must go before other textures
  12526. // not sure why, but otherwise weird things happen
  12527. if ( material.skinning ) {
  12528. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12529. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12530. var skeleton = object.skeleton;
  12531. if ( skeleton ) {
  12532. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12533. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12534. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12535. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12536. } else {
  12537. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12538. }
  12539. }
  12540. }
  12541. if ( refreshMaterial ) {
  12542. if ( material.lights ) {
  12543. // the current material requires lighting info
  12544. // note: all lighting uniforms are always set correctly
  12545. // they simply reference the renderer's state for their
  12546. // values
  12547. //
  12548. // use the current material's .needsUpdate flags to set
  12549. // the GL state when required
  12550. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12551. }
  12552. // refresh uniforms common to several materials
  12553. if ( fog && material.fog ) {
  12554. refreshUniformsFog( m_uniforms, fog );
  12555. }
  12556. if ( material.isMeshBasicMaterial ||
  12557. material.isMeshLambertMaterial ||
  12558. material.isMeshPhongMaterial ||
  12559. material.isMeshStandardMaterial ||
  12560. material.isMeshDepthMaterial ) {
  12561. refreshUniformsCommon( m_uniforms, material );
  12562. }
  12563. // refresh single material specific uniforms
  12564. if ( material.isLineBasicMaterial ) {
  12565. refreshUniformsLine( m_uniforms, material );
  12566. } else if ( material.isLineDashedMaterial ) {
  12567. refreshUniformsLine( m_uniforms, material );
  12568. refreshUniformsDash( m_uniforms, material );
  12569. } else if ( material.isPointsMaterial ) {
  12570. refreshUniformsPoints( m_uniforms, material );
  12571. } else if ( material.isMeshLambertMaterial ) {
  12572. refreshUniformsLambert( m_uniforms, material );
  12573. } else if ( material.isMeshPhongMaterial ) {
  12574. refreshUniformsPhong( m_uniforms, material );
  12575. } else if ( material.isMeshPhysicalMaterial ) {
  12576. refreshUniformsPhysical( m_uniforms, material );
  12577. } else if ( material.isMeshStandardMaterial ) {
  12578. refreshUniformsStandard( m_uniforms, material );
  12579. } else if ( material.isMeshDepthMaterial ) {
  12580. if ( material.displacementMap ) {
  12581. m_uniforms.displacementMap.value = material.displacementMap;
  12582. m_uniforms.displacementScale.value = material.displacementScale;
  12583. m_uniforms.displacementBias.value = material.displacementBias;
  12584. }
  12585. } else if ( material.isMeshNormalMaterial ) {
  12586. m_uniforms.opacity.value = material.opacity;
  12587. }
  12588. WebGLUniforms.upload(
  12589. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12590. }
  12591. // common matrices
  12592. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12593. p_uniforms.set( _gl, object, 'normalMatrix' );
  12594. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12595. // dynamic uniforms
  12596. var dynUniforms = materialProperties.dynamicUniforms;
  12597. if ( dynUniforms !== null ) {
  12598. WebGLUniforms.evalDynamic(
  12599. dynUniforms, m_uniforms, object, camera );
  12600. WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  12601. }
  12602. return program;
  12603. }
  12604. // Uniforms (refresh uniforms objects)
  12605. function refreshUniformsCommon( uniforms, material ) {
  12606. uniforms.opacity.value = material.opacity;
  12607. uniforms.diffuse.value = material.color;
  12608. if ( material.emissive ) {
  12609. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12610. }
  12611. uniforms.map.value = material.map;
  12612. uniforms.specularMap.value = material.specularMap;
  12613. uniforms.alphaMap.value = material.alphaMap;
  12614. if ( material.aoMap ) {
  12615. uniforms.aoMap.value = material.aoMap;
  12616. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12617. }
  12618. // uv repeat and offset setting priorities
  12619. // 1. color map
  12620. // 2. specular map
  12621. // 3. normal map
  12622. // 4. bump map
  12623. // 5. alpha map
  12624. // 6. emissive map
  12625. var uvScaleMap;
  12626. if ( material.map ) {
  12627. uvScaleMap = material.map;
  12628. } else if ( material.specularMap ) {
  12629. uvScaleMap = material.specularMap;
  12630. } else if ( material.displacementMap ) {
  12631. uvScaleMap = material.displacementMap;
  12632. } else if ( material.normalMap ) {
  12633. uvScaleMap = material.normalMap;
  12634. } else if ( material.bumpMap ) {
  12635. uvScaleMap = material.bumpMap;
  12636. } else if ( material.roughnessMap ) {
  12637. uvScaleMap = material.roughnessMap;
  12638. } else if ( material.metalnessMap ) {
  12639. uvScaleMap = material.metalnessMap;
  12640. } else if ( material.alphaMap ) {
  12641. uvScaleMap = material.alphaMap;
  12642. } else if ( material.emissiveMap ) {
  12643. uvScaleMap = material.emissiveMap;
  12644. }
  12645. if ( uvScaleMap !== undefined ) {
  12646. // backwards compatibility
  12647. if ( uvScaleMap.isWebGLRenderTarget ) {
  12648. uvScaleMap = uvScaleMap.texture;
  12649. }
  12650. var offset = uvScaleMap.offset;
  12651. var repeat = uvScaleMap.repeat;
  12652. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12653. }
  12654. uniforms.envMap.value = material.envMap;
  12655. // don't flip CubeTexture envMaps, flip everything else:
  12656. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12657. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12658. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12659. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12660. uniforms.reflectivity.value = material.reflectivity;
  12661. uniforms.refractionRatio.value = material.refractionRatio;
  12662. }
  12663. function refreshUniformsLine( uniforms, material ) {
  12664. uniforms.diffuse.value = material.color;
  12665. uniforms.opacity.value = material.opacity;
  12666. }
  12667. function refreshUniformsDash( uniforms, material ) {
  12668. uniforms.dashSize.value = material.dashSize;
  12669. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12670. uniforms.scale.value = material.scale;
  12671. }
  12672. function refreshUniformsPoints( uniforms, material ) {
  12673. uniforms.diffuse.value = material.color;
  12674. uniforms.opacity.value = material.opacity;
  12675. uniforms.size.value = material.size * _pixelRatio;
  12676. uniforms.scale.value = _canvas.clientHeight * 0.5;
  12677. uniforms.map.value = material.map;
  12678. if ( material.map !== null ) {
  12679. var offset = material.map.offset;
  12680. var repeat = material.map.repeat;
  12681. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12682. }
  12683. }
  12684. function refreshUniformsFog( uniforms, fog ) {
  12685. uniforms.fogColor.value = fog.color;
  12686. if ( fog.isFog ) {
  12687. uniforms.fogNear.value = fog.near;
  12688. uniforms.fogFar.value = fog.far;
  12689. } else if ( fog.isFogExp2 ) {
  12690. uniforms.fogDensity.value = fog.density;
  12691. }
  12692. }
  12693. function refreshUniformsLambert( uniforms, material ) {
  12694. if ( material.lightMap ) {
  12695. uniforms.lightMap.value = material.lightMap;
  12696. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12697. }
  12698. if ( material.emissiveMap ) {
  12699. uniforms.emissiveMap.value = material.emissiveMap;
  12700. }
  12701. }
  12702. function refreshUniformsPhong( uniforms, material ) {
  12703. uniforms.specular.value = material.specular;
  12704. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12705. if ( material.lightMap ) {
  12706. uniforms.lightMap.value = material.lightMap;
  12707. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12708. }
  12709. if ( material.emissiveMap ) {
  12710. uniforms.emissiveMap.value = material.emissiveMap;
  12711. }
  12712. if ( material.bumpMap ) {
  12713. uniforms.bumpMap.value = material.bumpMap;
  12714. uniforms.bumpScale.value = material.bumpScale;
  12715. }
  12716. if ( material.normalMap ) {
  12717. uniforms.normalMap.value = material.normalMap;
  12718. uniforms.normalScale.value.copy( material.normalScale );
  12719. }
  12720. if ( material.displacementMap ) {
  12721. uniforms.displacementMap.value = material.displacementMap;
  12722. uniforms.displacementScale.value = material.displacementScale;
  12723. uniforms.displacementBias.value = material.displacementBias;
  12724. }
  12725. }
  12726. function refreshUniformsStandard( uniforms, material ) {
  12727. uniforms.roughness.value = material.roughness;
  12728. uniforms.metalness.value = material.metalness;
  12729. if ( material.roughnessMap ) {
  12730. uniforms.roughnessMap.value = material.roughnessMap;
  12731. }
  12732. if ( material.metalnessMap ) {
  12733. uniforms.metalnessMap.value = material.metalnessMap;
  12734. }
  12735. if ( material.lightMap ) {
  12736. uniforms.lightMap.value = material.lightMap;
  12737. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12738. }
  12739. if ( material.emissiveMap ) {
  12740. uniforms.emissiveMap.value = material.emissiveMap;
  12741. }
  12742. if ( material.bumpMap ) {
  12743. uniforms.bumpMap.value = material.bumpMap;
  12744. uniforms.bumpScale.value = material.bumpScale;
  12745. }
  12746. if ( material.normalMap ) {
  12747. uniforms.normalMap.value = material.normalMap;
  12748. uniforms.normalScale.value.copy( material.normalScale );
  12749. }
  12750. if ( material.displacementMap ) {
  12751. uniforms.displacementMap.value = material.displacementMap;
  12752. uniforms.displacementScale.value = material.displacementScale;
  12753. uniforms.displacementBias.value = material.displacementBias;
  12754. }
  12755. if ( material.envMap ) {
  12756. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12757. uniforms.envMapIntensity.value = material.envMapIntensity;
  12758. }
  12759. }
  12760. function refreshUniformsPhysical( uniforms, material ) {
  12761. uniforms.clearCoat.value = material.clearCoat;
  12762. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12763. refreshUniformsStandard( uniforms, material );
  12764. }
  12765. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12766. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12767. uniforms.ambientLightColor.needsUpdate = value;
  12768. uniforms.directionalLights.needsUpdate = value;
  12769. uniforms.pointLights.needsUpdate = value;
  12770. uniforms.spotLights.needsUpdate = value;
  12771. uniforms.hemisphereLights.needsUpdate = value;
  12772. }
  12773. // Lighting
  12774. function setupShadows( lights ) {
  12775. var lightShadowsLength = 0;
  12776. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12777. var light = lights[ i ];
  12778. if ( light.castShadow ) {
  12779. _lights.shadows[ lightShadowsLength ++ ] = light;
  12780. }
  12781. }
  12782. _lights.shadows.length = lightShadowsLength;
  12783. }
  12784. function setupLights( lights, camera ) {
  12785. var l, ll, light,
  12786. r = 0, g = 0, b = 0,
  12787. color,
  12788. intensity,
  12789. distance,
  12790. shadowMap,
  12791. viewMatrix = camera.matrixWorldInverse,
  12792. directionalLength = 0,
  12793. pointLength = 0,
  12794. spotLength = 0,
  12795. hemiLength = 0;
  12796. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12797. light = lights[ l ];
  12798. color = light.color;
  12799. intensity = light.intensity;
  12800. distance = light.distance;
  12801. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12802. if ( light.isAmbientLight ) {
  12803. r += color.r * intensity;
  12804. g += color.g * intensity;
  12805. b += color.b * intensity;
  12806. } else if ( light.isDirectionalLight ) {
  12807. var uniforms = lightCache.get( light );
  12808. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12809. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12810. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12811. uniforms.direction.sub( _vector3 );
  12812. uniforms.direction.transformDirection( viewMatrix );
  12813. uniforms.shadow = light.castShadow;
  12814. if ( light.castShadow ) {
  12815. uniforms.shadowBias = light.shadow.bias;
  12816. uniforms.shadowRadius = light.shadow.radius;
  12817. uniforms.shadowMapSize = light.shadow.mapSize;
  12818. }
  12819. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12820. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12821. _lights.directional[ directionalLength ++ ] = uniforms;
  12822. } else if ( light.isSpotLight ) {
  12823. var uniforms = lightCache.get( light );
  12824. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12825. uniforms.position.applyMatrix4( viewMatrix );
  12826. uniforms.color.copy( color ).multiplyScalar( intensity );
  12827. uniforms.distance = distance;
  12828. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12829. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12830. uniforms.direction.sub( _vector3 );
  12831. uniforms.direction.transformDirection( viewMatrix );
  12832. uniforms.coneCos = Math.cos( light.angle );
  12833. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12834. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12835. uniforms.shadow = light.castShadow;
  12836. if ( light.castShadow ) {
  12837. uniforms.shadowBias = light.shadow.bias;
  12838. uniforms.shadowRadius = light.shadow.radius;
  12839. uniforms.shadowMapSize = light.shadow.mapSize;
  12840. }
  12841. _lights.spotShadowMap[ spotLength ] = shadowMap;
  12842. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12843. _lights.spot[ spotLength ++ ] = uniforms;
  12844. } else if ( light.isPointLight ) {
  12845. var uniforms = lightCache.get( light );
  12846. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12847. uniforms.position.applyMatrix4( viewMatrix );
  12848. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12849. uniforms.distance = light.distance;
  12850. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12851. uniforms.shadow = light.castShadow;
  12852. if ( light.castShadow ) {
  12853. uniforms.shadowBias = light.shadow.bias;
  12854. uniforms.shadowRadius = light.shadow.radius;
  12855. uniforms.shadowMapSize = light.shadow.mapSize;
  12856. }
  12857. _lights.pointShadowMap[ pointLength ] = shadowMap;
  12858. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  12859. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  12860. }
  12861. // for point lights we set the shadow matrix to be a translation-only matrix
  12862. // equal to inverse of the light's position
  12863. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  12864. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  12865. _lights.point[ pointLength ++ ] = uniforms;
  12866. } else if ( light.isHemisphereLight ) {
  12867. var uniforms = lightCache.get( light );
  12868. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12869. uniforms.direction.transformDirection( viewMatrix );
  12870. uniforms.direction.normalize();
  12871. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  12872. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  12873. _lights.hemi[ hemiLength ++ ] = uniforms;
  12874. }
  12875. }
  12876. _lights.ambient[ 0 ] = r;
  12877. _lights.ambient[ 1 ] = g;
  12878. _lights.ambient[ 2 ] = b;
  12879. _lights.directional.length = directionalLength;
  12880. _lights.spot.length = spotLength;
  12881. _lights.point.length = pointLength;
  12882. _lights.hemi.length = hemiLength;
  12883. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  12884. }
  12885. // GL state setting
  12886. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12887. state.setCullFace( cullFace );
  12888. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  12889. };
  12890. // Textures
  12891. function allocTextureUnit() {
  12892. var textureUnit = _usedTextureUnits;
  12893. if ( textureUnit >= capabilities.maxTextures ) {
  12894. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  12895. }
  12896. _usedTextureUnits += 1;
  12897. return textureUnit;
  12898. }
  12899. this.allocTextureUnit = allocTextureUnit;
  12900. // this.setTexture2D = setTexture2D;
  12901. this.setTexture2D = ( function() {
  12902. var warned = false;
  12903. // backwards compatibility: peel texture.texture
  12904. return function setTexture2D( texture, slot ) {
  12905. if ( texture && texture.isWebGLRenderTarget ) {
  12906. if ( ! warned ) {
  12907. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  12908. warned = true;
  12909. }
  12910. texture = texture.texture;
  12911. }
  12912. textures.setTexture2D( texture, slot );
  12913. };
  12914. }() );
  12915. this.setTexture = ( function() {
  12916. var warned = false;
  12917. return function setTexture( texture, slot ) {
  12918. if ( ! warned ) {
  12919. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  12920. warned = true;
  12921. }
  12922. textures.setTexture2D( texture, slot );
  12923. };
  12924. }() );
  12925. this.setTextureCube = ( function() {
  12926. var warned = false;
  12927. return function setTextureCube( texture, slot ) {
  12928. // backwards compatibility: peel texture.texture
  12929. if ( texture && texture.isWebGLRenderTargetCube ) {
  12930. if ( ! warned ) {
  12931. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  12932. warned = true;
  12933. }
  12934. texture = texture.texture;
  12935. }
  12936. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  12937. // TODO: unify these code paths
  12938. if ( ( texture && texture.isCubeTexture ) ||
  12939. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  12940. // CompressedTexture can have Array in image :/
  12941. // this function alone should take care of cube textures
  12942. textures.setTextureCube( texture, slot );
  12943. } else {
  12944. // assumed: texture property of THREE.WebGLRenderTargetCube
  12945. textures.setTextureCubeDynamic( texture, slot );
  12946. }
  12947. };
  12948. }() );
  12949. this.getCurrentRenderTarget = function() {
  12950. return _currentRenderTarget;
  12951. };
  12952. this.setRenderTarget = function ( renderTarget ) {
  12953. _currentRenderTarget = renderTarget;
  12954. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  12955. textures.setupRenderTarget( renderTarget );
  12956. }
  12957. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  12958. var framebuffer;
  12959. if ( renderTarget ) {
  12960. var renderTargetProperties = properties.get( renderTarget );
  12961. if ( isCube ) {
  12962. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12963. } else {
  12964. framebuffer = renderTargetProperties.__webglFramebuffer;
  12965. }
  12966. _currentScissor.copy( renderTarget.scissor );
  12967. _currentScissorTest = renderTarget.scissorTest;
  12968. _currentViewport.copy( renderTarget.viewport );
  12969. } else {
  12970. framebuffer = null;
  12971. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  12972. _currentScissorTest = _scissorTest;
  12973. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  12974. }
  12975. if ( _currentFramebuffer !== framebuffer ) {
  12976. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12977. _currentFramebuffer = framebuffer;
  12978. }
  12979. state.scissor( _currentScissor );
  12980. state.setScissorTest( _currentScissorTest );
  12981. state.viewport( _currentViewport );
  12982. if ( isCube ) {
  12983. var textureProperties = properties.get( renderTarget.texture );
  12984. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  12985. }
  12986. };
  12987. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  12988. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  12989. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  12990. return;
  12991. }
  12992. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  12993. if ( framebuffer ) {
  12994. var restore = false;
  12995. if ( framebuffer !== _currentFramebuffer ) {
  12996. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12997. restore = true;
  12998. }
  12999. try {
  13000. var texture = renderTarget.texture;
  13001. var textureFormat = texture.format;
  13002. var textureType = texture.type;
  13003. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13004. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13005. return;
  13006. }
  13007. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13008. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13009. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13010. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13011. return;
  13012. }
  13013. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13014. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13015. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13016. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13017. }
  13018. } else {
  13019. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13020. }
  13021. } finally {
  13022. if ( restore ) {
  13023. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13024. }
  13025. }
  13026. }
  13027. };
  13028. // Map three.js constants to WebGL constants
  13029. function paramThreeToGL( p ) {
  13030. var extension;
  13031. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13032. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13033. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13034. if ( p === NearestFilter ) return _gl.NEAREST;
  13035. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13036. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13037. if ( p === LinearFilter ) return _gl.LINEAR;
  13038. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13039. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13040. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13041. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13042. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13043. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13044. if ( p === ByteType ) return _gl.BYTE;
  13045. if ( p === ShortType ) return _gl.SHORT;
  13046. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13047. if ( p === IntType ) return _gl.INT;
  13048. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13049. if ( p === FloatType ) return _gl.FLOAT;
  13050. extension = extensions.get( 'OES_texture_half_float' );
  13051. if ( extension !== null ) {
  13052. if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES;
  13053. }
  13054. if ( p === AlphaFormat ) return _gl.ALPHA;
  13055. if ( p === RGBFormat ) return _gl.RGB;
  13056. if ( p === RGBAFormat ) return _gl.RGBA;
  13057. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13058. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13059. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13060. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13061. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13062. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13063. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13064. if ( p === ZeroFactor ) return _gl.ZERO;
  13065. if ( p === OneFactor ) return _gl.ONE;
  13066. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13067. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13068. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13069. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13070. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13071. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13072. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13073. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13074. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13075. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13076. if ( extension !== null ) {
  13077. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13078. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13079. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13080. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13081. }
  13082. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13083. if ( extension !== null ) {
  13084. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13085. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13086. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13087. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13088. }
  13089. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13090. if ( extension !== null ) {
  13091. if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13092. }
  13093. extension = extensions.get( 'EXT_blend_minmax' );
  13094. if ( extension !== null ) {
  13095. if ( p === MinEquation ) return extension.MIN_EXT;
  13096. if ( p === MaxEquation ) return extension.MAX_EXT;
  13097. }
  13098. extension = extensions.get( 'WEBGL_depth_texture' );
  13099. if ( extension !== null ){
  13100. if ( p === UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13101. }
  13102. return 0;
  13103. }
  13104. }
  13105. /**
  13106. * @author mrdoob / http://mrdoob.com/
  13107. * @author alteredq / http://alteredqualia.com/
  13108. */
  13109. function FogExp2 ( color, density ) {
  13110. this.name = '';
  13111. this.color = new Color( color );
  13112. this.density = ( density !== undefined ) ? density : 0.00025;
  13113. }
  13114. FogExp2.prototype.isFogExp2 = true;
  13115. FogExp2.prototype.clone = function () {
  13116. return new FogExp2( this.color.getHex(), this.density );
  13117. };
  13118. FogExp2.prototype.toJSON = function ( meta ) {
  13119. return {
  13120. type: 'FogExp2',
  13121. color: this.color.getHex(),
  13122. density: this.density
  13123. };
  13124. };
  13125. /**
  13126. * @author mrdoob / http://mrdoob.com/
  13127. * @author alteredq / http://alteredqualia.com/
  13128. */
  13129. function Fog ( color, near, far ) {
  13130. this.name = '';
  13131. this.color = new Color( color );
  13132. this.near = ( near !== undefined ) ? near : 1;
  13133. this.far = ( far !== undefined ) ? far : 1000;
  13134. }
  13135. Fog.prototype.isFog = true;
  13136. Fog.prototype.clone = function () {
  13137. return new Fog( this.color.getHex(), this.near, this.far );
  13138. };
  13139. Fog.prototype.toJSON = function ( meta ) {
  13140. return {
  13141. type: 'Fog',
  13142. color: this.color.getHex(),
  13143. near: this.near,
  13144. far: this.far
  13145. };
  13146. };
  13147. /**
  13148. * @author mrdoob / http://mrdoob.com/
  13149. */
  13150. function Scene () {
  13151. Object3D.call( this );
  13152. this.type = 'Scene';
  13153. this.background = null;
  13154. this.fog = null;
  13155. this.overrideMaterial = null;
  13156. this.autoUpdate = true; // checked by the renderer
  13157. }
  13158. Scene.prototype = Object.create( Object3D.prototype );
  13159. Scene.prototype.constructor = Scene;
  13160. Scene.prototype.copy = function ( source, recursive ) {
  13161. Object3D.prototype.copy.call( this, source, recursive );
  13162. if ( source.background !== null ) this.background = source.background.clone();
  13163. if ( source.fog !== null ) this.fog = source.fog.clone();
  13164. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13165. this.autoUpdate = source.autoUpdate;
  13166. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13167. return this;
  13168. };
  13169. Scene.prototype.toJSON = function ( meta ) {
  13170. var data = Object3D.prototype.toJSON.call( this, meta );
  13171. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13172. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13173. return data;
  13174. };
  13175. /**
  13176. * @author mikael emtinger / http://gomo.se/
  13177. * @author alteredq / http://alteredqualia.com/
  13178. */
  13179. function LensFlare( texture, size, distance, blending, color ) {
  13180. Object3D.call( this );
  13181. this.lensFlares = [];
  13182. this.positionScreen = new Vector3();
  13183. this.customUpdateCallback = undefined;
  13184. if ( texture !== undefined ) {
  13185. this.add( texture, size, distance, blending, color );
  13186. }
  13187. }
  13188. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13189. constructor: LensFlare,
  13190. isLensFlare: true,
  13191. copy: function ( source ) {
  13192. Object3D.prototype.copy.call( this, source );
  13193. this.positionScreen.copy( source.positionScreen );
  13194. this.customUpdateCallback = source.customUpdateCallback;
  13195. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13196. this.lensFlares.push( source.lensFlares[ i ] );
  13197. }
  13198. return this;
  13199. },
  13200. add: function ( texture, size, distance, blending, color, opacity ) {
  13201. if ( size === undefined ) size = - 1;
  13202. if ( distance === undefined ) distance = 0;
  13203. if ( opacity === undefined ) opacity = 1;
  13204. if ( color === undefined ) color = new Color( 0xffffff );
  13205. if ( blending === undefined ) blending = NormalBlending;
  13206. distance = Math.min( distance, Math.max( 0, distance ) );
  13207. this.lensFlares.push( {
  13208. texture: texture, // THREE.Texture
  13209. size: size, // size in pixels (-1 = use texture.width)
  13210. distance: distance, // distance (0-1) from light source (0=at light source)
  13211. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13212. scale: 1, // scale
  13213. rotation: 0, // rotation
  13214. opacity: opacity, // opacity
  13215. color: color, // color
  13216. blending: blending // blending
  13217. } );
  13218. },
  13219. /*
  13220. * Update lens flares update positions on all flares based on the screen position
  13221. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13222. */
  13223. updateLensFlares: function () {
  13224. var f, fl = this.lensFlares.length;
  13225. var flare;
  13226. var vecX = - this.positionScreen.x * 2;
  13227. var vecY = - this.positionScreen.y * 2;
  13228. for ( f = 0; f < fl; f ++ ) {
  13229. flare = this.lensFlares[ f ];
  13230. flare.x = this.positionScreen.x + vecX * flare.distance;
  13231. flare.y = this.positionScreen.y + vecY * flare.distance;
  13232. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13233. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13234. }
  13235. }
  13236. } );
  13237. /**
  13238. * @author alteredq / http://alteredqualia.com/
  13239. *
  13240. * parameters = {
  13241. * color: <hex>,
  13242. * opacity: <float>,
  13243. * map: new THREE.Texture( <Image> ),
  13244. *
  13245. * uvOffset: new THREE.Vector2(),
  13246. * uvScale: new THREE.Vector2()
  13247. * }
  13248. */
  13249. function SpriteMaterial( parameters ) {
  13250. Material.call( this );
  13251. this.type = 'SpriteMaterial';
  13252. this.color = new Color( 0xffffff );
  13253. this.map = null;
  13254. this.rotation = 0;
  13255. this.fog = false;
  13256. this.lights = false;
  13257. this.setValues( parameters );
  13258. }
  13259. SpriteMaterial.prototype = Object.create( Material.prototype );
  13260. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13261. SpriteMaterial.prototype.copy = function ( source ) {
  13262. Material.prototype.copy.call( this, source );
  13263. this.color.copy( source.color );
  13264. this.map = source.map;
  13265. this.rotation = source.rotation;
  13266. return this;
  13267. };
  13268. /**
  13269. * @author mikael emtinger / http://gomo.se/
  13270. * @author alteredq / http://alteredqualia.com/
  13271. */
  13272. function Sprite( material ) {
  13273. Object3D.call( this );
  13274. this.type = 'Sprite';
  13275. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13276. }
  13277. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13278. constructor: Sprite,
  13279. isSprite: true,
  13280. raycast: ( function () {
  13281. var matrixPosition = new Vector3();
  13282. return function raycast( raycaster, intersects ) {
  13283. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13284. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13285. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13286. if ( distanceSq > guessSizeSq ) {
  13287. return;
  13288. }
  13289. intersects.push( {
  13290. distance: Math.sqrt( distanceSq ),
  13291. point: this.position,
  13292. face: null,
  13293. object: this
  13294. } );
  13295. };
  13296. }() ),
  13297. clone: function () {
  13298. return new this.constructor( this.material ).copy( this );
  13299. }
  13300. } );
  13301. /**
  13302. * @author mikael emtinger / http://gomo.se/
  13303. * @author alteredq / http://alteredqualia.com/
  13304. * @author mrdoob / http://mrdoob.com/
  13305. */
  13306. function LOD() {
  13307. Object3D.call( this );
  13308. this.type = 'LOD';
  13309. Object.defineProperties( this, {
  13310. levels: {
  13311. enumerable: true,
  13312. value: []
  13313. }
  13314. } );
  13315. }
  13316. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13317. constructor: LOD,
  13318. copy: function ( source ) {
  13319. Object3D.prototype.copy.call( this, source, false );
  13320. var levels = source.levels;
  13321. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13322. var level = levels[ i ];
  13323. this.addLevel( level.object.clone(), level.distance );
  13324. }
  13325. return this;
  13326. },
  13327. addLevel: function ( object, distance ) {
  13328. if ( distance === undefined ) distance = 0;
  13329. distance = Math.abs( distance );
  13330. var levels = this.levels;
  13331. for ( var l = 0; l < levels.length; l ++ ) {
  13332. if ( distance < levels[ l ].distance ) {
  13333. break;
  13334. }
  13335. }
  13336. levels.splice( l, 0, { distance: distance, object: object } );
  13337. this.add( object );
  13338. },
  13339. getObjectForDistance: function ( distance ) {
  13340. var levels = this.levels;
  13341. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13342. if ( distance < levels[ i ].distance ) {
  13343. break;
  13344. }
  13345. }
  13346. return levels[ i - 1 ].object;
  13347. },
  13348. raycast: ( function () {
  13349. var matrixPosition = new Vector3();
  13350. return function raycast( raycaster, intersects ) {
  13351. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13352. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13353. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13354. };
  13355. }() ),
  13356. update: function () {
  13357. var v1 = new Vector3();
  13358. var v2 = new Vector3();
  13359. return function update( camera ) {
  13360. var levels = this.levels;
  13361. if ( levels.length > 1 ) {
  13362. v1.setFromMatrixPosition( camera.matrixWorld );
  13363. v2.setFromMatrixPosition( this.matrixWorld );
  13364. var distance = v1.distanceTo( v2 );
  13365. levels[ 0 ].object.visible = true;
  13366. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13367. if ( distance >= levels[ i ].distance ) {
  13368. levels[ i - 1 ].object.visible = false;
  13369. levels[ i ].object.visible = true;
  13370. } else {
  13371. break;
  13372. }
  13373. }
  13374. for ( ; i < l; i ++ ) {
  13375. levels[ i ].object.visible = false;
  13376. }
  13377. }
  13378. };
  13379. }(),
  13380. toJSON: function ( meta ) {
  13381. var data = Object3D.prototype.toJSON.call( this, meta );
  13382. data.object.levels = [];
  13383. var levels = this.levels;
  13384. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13385. var level = levels[ i ];
  13386. data.object.levels.push( {
  13387. object: level.object.uuid,
  13388. distance: level.distance
  13389. } );
  13390. }
  13391. return data;
  13392. }
  13393. } );
  13394. /**
  13395. * @author alteredq / http://alteredqualia.com/
  13396. */
  13397. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13398. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13399. this.image = { data: data, width: width, height: height };
  13400. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13401. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13402. this.flipY = false;
  13403. this.generateMipmaps = false;
  13404. }
  13405. DataTexture.prototype = Object.create( Texture.prototype );
  13406. DataTexture.prototype.constructor = DataTexture;
  13407. DataTexture.prototype.isDataTexture = true;
  13408. /**
  13409. * @author mikael emtinger / http://gomo.se/
  13410. * @author alteredq / http://alteredqualia.com/
  13411. * @author michael guerrero / http://realitymeltdown.com
  13412. * @author ikerr / http://verold.com
  13413. */
  13414. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13415. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13416. this.identityMatrix = new Matrix4();
  13417. // copy the bone array
  13418. bones = bones || [];
  13419. this.bones = bones.slice( 0 );
  13420. // create a bone texture or an array of floats
  13421. if ( this.useVertexTexture ) {
  13422. // layout (1 matrix = 4 pixels)
  13423. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13424. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13425. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13426. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13427. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13428. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13429. size = exports.Math.nextPowerOfTwo( Math.ceil( size ) );
  13430. size = Math.max( size, 4 );
  13431. this.boneTextureWidth = size;
  13432. this.boneTextureHeight = size;
  13433. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13434. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13435. } else {
  13436. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13437. }
  13438. // use the supplied bone inverses or calculate the inverses
  13439. if ( boneInverses === undefined ) {
  13440. this.calculateInverses();
  13441. } else {
  13442. if ( this.bones.length === boneInverses.length ) {
  13443. this.boneInverses = boneInverses.slice( 0 );
  13444. } else {
  13445. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13446. this.boneInverses = [];
  13447. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13448. this.boneInverses.push( new Matrix4() );
  13449. }
  13450. }
  13451. }
  13452. }
  13453. Object.assign( Skeleton.prototype, {
  13454. calculateInverses: function () {
  13455. this.boneInverses = [];
  13456. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13457. var inverse = new Matrix4();
  13458. if ( this.bones[ b ] ) {
  13459. inverse.getInverse( this.bones[ b ].matrixWorld );
  13460. }
  13461. this.boneInverses.push( inverse );
  13462. }
  13463. },
  13464. pose: function () {
  13465. var bone;
  13466. // recover the bind-time world matrices
  13467. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13468. bone = this.bones[ b ];
  13469. if ( bone ) {
  13470. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13471. }
  13472. }
  13473. // compute the local matrices, positions, rotations and scales
  13474. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13475. bone = this.bones[ b ];
  13476. if ( bone ) {
  13477. if ( (bone.parent && bone.parent.isBone) ) {
  13478. bone.matrix.getInverse( bone.parent.matrixWorld );
  13479. bone.matrix.multiply( bone.matrixWorld );
  13480. } else {
  13481. bone.matrix.copy( bone.matrixWorld );
  13482. }
  13483. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13484. }
  13485. }
  13486. },
  13487. update: ( function () {
  13488. var offsetMatrix = new Matrix4();
  13489. return function update() {
  13490. // flatten bone matrices to array
  13491. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13492. // compute the offset between the current and the original transform
  13493. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13494. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13495. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13496. }
  13497. if ( this.useVertexTexture ) {
  13498. this.boneTexture.needsUpdate = true;
  13499. }
  13500. };
  13501. } )(),
  13502. clone: function () {
  13503. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13504. }
  13505. } );
  13506. /**
  13507. * @author mikael emtinger / http://gomo.se/
  13508. * @author alteredq / http://alteredqualia.com/
  13509. * @author ikerr / http://verold.com
  13510. */
  13511. function Bone( skin ) {
  13512. Object3D.call( this );
  13513. this.type = 'Bone';
  13514. this.skin = skin;
  13515. }
  13516. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13517. constructor: Bone,
  13518. isBone: true,
  13519. copy: function ( source ) {
  13520. Object3D.prototype.copy.call( this, source );
  13521. this.skin = source.skin;
  13522. return this;
  13523. }
  13524. } );
  13525. /**
  13526. * @author mikael emtinger / http://gomo.se/
  13527. * @author alteredq / http://alteredqualia.com/
  13528. * @author ikerr / http://verold.com
  13529. */
  13530. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13531. Mesh.call( this, geometry, material );
  13532. this.type = 'SkinnedMesh';
  13533. this.bindMode = "attached";
  13534. this.bindMatrix = new Matrix4();
  13535. this.bindMatrixInverse = new Matrix4();
  13536. // init bones
  13537. // TODO: remove bone creation as there is no reason (other than
  13538. // convenience) for THREE.SkinnedMesh to do this.
  13539. var bones = [];
  13540. if ( this.geometry && this.geometry.bones !== undefined ) {
  13541. var bone, gbone;
  13542. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13543. gbone = this.geometry.bones[ b ];
  13544. bone = new Bone( this );
  13545. bones.push( bone );
  13546. bone.name = gbone.name;
  13547. bone.position.fromArray( gbone.pos );
  13548. bone.quaternion.fromArray( gbone.rotq );
  13549. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13550. }
  13551. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13552. gbone = this.geometry.bones[ b ];
  13553. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13554. bones[ gbone.parent ] !== undefined ) {
  13555. bones[ gbone.parent ].add( bones[ b ] );
  13556. } else {
  13557. this.add( bones[ b ] );
  13558. }
  13559. }
  13560. }
  13561. this.normalizeSkinWeights();
  13562. this.updateMatrixWorld( true );
  13563. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13564. }
  13565. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13566. constructor: SkinnedMesh,
  13567. isSkinnedMesh: true,
  13568. bind: function( skeleton, bindMatrix ) {
  13569. this.skeleton = skeleton;
  13570. if ( bindMatrix === undefined ) {
  13571. this.updateMatrixWorld( true );
  13572. this.skeleton.calculateInverses();
  13573. bindMatrix = this.matrixWorld;
  13574. }
  13575. this.bindMatrix.copy( bindMatrix );
  13576. this.bindMatrixInverse.getInverse( bindMatrix );
  13577. },
  13578. pose: function () {
  13579. this.skeleton.pose();
  13580. },
  13581. normalizeSkinWeights: function () {
  13582. if ( (this.geometry && this.geometry.isGeometry) ) {
  13583. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13584. var sw = this.geometry.skinWeights[ i ];
  13585. var scale = 1.0 / sw.lengthManhattan();
  13586. if ( scale !== Infinity ) {
  13587. sw.multiplyScalar( scale );
  13588. } else {
  13589. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13590. }
  13591. }
  13592. } else if ( (this.geometry && this.geometry.isBufferGeometry) ) {
  13593. var vec = new Vector4();
  13594. var skinWeight = this.geometry.attributes.skinWeight;
  13595. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13596. vec.x = skinWeight.getX( i );
  13597. vec.y = skinWeight.getY( i );
  13598. vec.z = skinWeight.getZ( i );
  13599. vec.w = skinWeight.getW( i );
  13600. var scale = 1.0 / vec.lengthManhattan();
  13601. if ( scale !== Infinity ) {
  13602. vec.multiplyScalar( scale );
  13603. } else {
  13604. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13605. }
  13606. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13607. }
  13608. }
  13609. },
  13610. updateMatrixWorld: function( force ) {
  13611. Mesh.prototype.updateMatrixWorld.call( this, true );
  13612. if ( this.bindMode === "attached" ) {
  13613. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13614. } else if ( this.bindMode === "detached" ) {
  13615. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13616. } else {
  13617. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13618. }
  13619. },
  13620. clone: function() {
  13621. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13622. }
  13623. } );
  13624. /**
  13625. * @author mrdoob / http://mrdoob.com/
  13626. * @author alteredq / http://alteredqualia.com/
  13627. *
  13628. * parameters = {
  13629. * color: <hex>,
  13630. * opacity: <float>,
  13631. *
  13632. * linewidth: <float>,
  13633. * linecap: "round",
  13634. * linejoin: "round"
  13635. * }
  13636. */
  13637. function LineBasicMaterial( parameters ) {
  13638. Material.call( this );
  13639. this.type = 'LineBasicMaterial';
  13640. this.color = new Color( 0xffffff );
  13641. this.linewidth = 1;
  13642. this.linecap = 'round';
  13643. this.linejoin = 'round';
  13644. this.lights = false;
  13645. this.setValues( parameters );
  13646. }
  13647. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13648. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13649. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13650. LineBasicMaterial.prototype.copy = function ( source ) {
  13651. Material.prototype.copy.call( this, source );
  13652. this.color.copy( source.color );
  13653. this.linewidth = source.linewidth;
  13654. this.linecap = source.linecap;
  13655. this.linejoin = source.linejoin;
  13656. return this;
  13657. };
  13658. /**
  13659. * @author mrdoob / http://mrdoob.com/
  13660. */
  13661. function Line( geometry, material, mode ) {
  13662. if ( mode === 1 ) {
  13663. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13664. return new LineSegments( geometry, material );
  13665. }
  13666. Object3D.call( this );
  13667. this.type = 'Line';
  13668. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13669. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13670. }
  13671. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13672. constructor: Line,
  13673. isLine: true,
  13674. raycast: ( function () {
  13675. var inverseMatrix = new Matrix4();
  13676. var ray = new Ray();
  13677. var sphere = new Sphere();
  13678. return function raycast( raycaster, intersects ) {
  13679. var precision = raycaster.linePrecision;
  13680. var precisionSq = precision * precision;
  13681. var geometry = this.geometry;
  13682. var matrixWorld = this.matrixWorld;
  13683. // Checking boundingSphere distance to ray
  13684. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13685. sphere.copy( geometry.boundingSphere );
  13686. sphere.applyMatrix4( matrixWorld );
  13687. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13688. //
  13689. inverseMatrix.getInverse( matrixWorld );
  13690. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13691. var vStart = new Vector3();
  13692. var vEnd = new Vector3();
  13693. var interSegment = new Vector3();
  13694. var interRay = new Vector3();
  13695. var step = (this && this.isLineSegments) ? 2 : 1;
  13696. if ( (geometry && geometry.isBufferGeometry) ) {
  13697. var index = geometry.index;
  13698. var attributes = geometry.attributes;
  13699. var positions = attributes.position.array;
  13700. if ( index !== null ) {
  13701. var indices = index.array;
  13702. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13703. var a = indices[ i ];
  13704. var b = indices[ i + 1 ];
  13705. vStart.fromArray( positions, a * 3 );
  13706. vEnd.fromArray( positions, b * 3 );
  13707. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13708. if ( distSq > precisionSq ) continue;
  13709. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13710. var distance = raycaster.ray.origin.distanceTo( interRay );
  13711. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13712. intersects.push( {
  13713. distance: distance,
  13714. // What do we want? intersection point on the ray or on the segment??
  13715. // point: raycaster.ray.at( distance ),
  13716. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13717. index: i,
  13718. face: null,
  13719. faceIndex: null,
  13720. object: this
  13721. } );
  13722. }
  13723. } else {
  13724. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13725. vStart.fromArray( positions, 3 * i );
  13726. vEnd.fromArray( positions, 3 * i + 3 );
  13727. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13728. if ( distSq > precisionSq ) continue;
  13729. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13730. var distance = raycaster.ray.origin.distanceTo( interRay );
  13731. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13732. intersects.push( {
  13733. distance: distance,
  13734. // What do we want? intersection point on the ray or on the segment??
  13735. // point: raycaster.ray.at( distance ),
  13736. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13737. index: i,
  13738. face: null,
  13739. faceIndex: null,
  13740. object: this
  13741. } );
  13742. }
  13743. }
  13744. } else if ( (geometry && geometry.isGeometry) ) {
  13745. var vertices = geometry.vertices;
  13746. var nbVertices = vertices.length;
  13747. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13748. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13749. if ( distSq > precisionSq ) continue;
  13750. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13751. var distance = raycaster.ray.origin.distanceTo( interRay );
  13752. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13753. intersects.push( {
  13754. distance: distance,
  13755. // What do we want? intersection point on the ray or on the segment??
  13756. // point: raycaster.ray.at( distance ),
  13757. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13758. index: i,
  13759. face: null,
  13760. faceIndex: null,
  13761. object: this
  13762. } );
  13763. }
  13764. }
  13765. };
  13766. }() ),
  13767. clone: function () {
  13768. return new this.constructor( this.geometry, this.material ).copy( this );
  13769. }
  13770. } );
  13771. /**
  13772. * @author mrdoob / http://mrdoob.com/
  13773. */
  13774. function LineSegments( geometry, material ) {
  13775. Line.call( this, geometry, material );
  13776. this.type = 'LineSegments';
  13777. }
  13778. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13779. constructor: LineSegments,
  13780. isLineSegments: true
  13781. } );
  13782. /**
  13783. * @author mrdoob / http://mrdoob.com/
  13784. * @author alteredq / http://alteredqualia.com/
  13785. *
  13786. * parameters = {
  13787. * color: <hex>,
  13788. * opacity: <float>,
  13789. * map: new THREE.Texture( <Image> ),
  13790. *
  13791. * size: <float>,
  13792. * sizeAttenuation: <bool>
  13793. * }
  13794. */
  13795. function PointsMaterial( parameters ) {
  13796. Material.call( this );
  13797. this.type = 'PointsMaterial';
  13798. this.color = new Color( 0xffffff );
  13799. this.map = null;
  13800. this.size = 1;
  13801. this.sizeAttenuation = true;
  13802. this.lights = false;
  13803. this.setValues( parameters );
  13804. }
  13805. PointsMaterial.prototype = Object.create( Material.prototype );
  13806. PointsMaterial.prototype.constructor = PointsMaterial;
  13807. PointsMaterial.prototype.isPointsMaterial = true;
  13808. PointsMaterial.prototype.copy = function ( source ) {
  13809. Material.prototype.copy.call( this, source );
  13810. this.color.copy( source.color );
  13811. this.map = source.map;
  13812. this.size = source.size;
  13813. this.sizeAttenuation = source.sizeAttenuation;
  13814. return this;
  13815. };
  13816. /**
  13817. * @author alteredq / http://alteredqualia.com/
  13818. */
  13819. function Points( geometry, material ) {
  13820. Object3D.call( this );
  13821. this.type = 'Points';
  13822. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13823. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  13824. }
  13825. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13826. constructor: Points,
  13827. isPoints: true,
  13828. raycast: ( function () {
  13829. var inverseMatrix = new Matrix4();
  13830. var ray = new Ray();
  13831. var sphere = new Sphere();
  13832. return function raycast( raycaster, intersects ) {
  13833. var object = this;
  13834. var geometry = this.geometry;
  13835. var matrixWorld = this.matrixWorld;
  13836. var threshold = raycaster.params.Points.threshold;
  13837. // Checking boundingSphere distance to ray
  13838. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13839. sphere.copy( geometry.boundingSphere );
  13840. sphere.applyMatrix4( matrixWorld );
  13841. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13842. //
  13843. inverseMatrix.getInverse( matrixWorld );
  13844. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13845. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13846. var localThresholdSq = localThreshold * localThreshold;
  13847. var position = new Vector3();
  13848. function testPoint( point, index ) {
  13849. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13850. if ( rayPointDistanceSq < localThresholdSq ) {
  13851. var intersectPoint = ray.closestPointToPoint( point );
  13852. intersectPoint.applyMatrix4( matrixWorld );
  13853. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13854. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13855. intersects.push( {
  13856. distance: distance,
  13857. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13858. point: intersectPoint.clone(),
  13859. index: index,
  13860. face: null,
  13861. object: object
  13862. } );
  13863. }
  13864. }
  13865. if ( (geometry && geometry.isBufferGeometry) ) {
  13866. var index = geometry.index;
  13867. var attributes = geometry.attributes;
  13868. var positions = attributes.position.array;
  13869. if ( index !== null ) {
  13870. var indices = index.array;
  13871. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13872. var a = indices[ i ];
  13873. position.fromArray( positions, a * 3 );
  13874. testPoint( position, a );
  13875. }
  13876. } else {
  13877. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13878. position.fromArray( positions, i * 3 );
  13879. testPoint( position, i );
  13880. }
  13881. }
  13882. } else {
  13883. var vertices = geometry.vertices;
  13884. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13885. testPoint( vertices[ i ], i );
  13886. }
  13887. }
  13888. };
  13889. }() ),
  13890. clone: function () {
  13891. return new this.constructor( this.geometry, this.material ).copy( this );
  13892. }
  13893. } );
  13894. /**
  13895. * @author mrdoob / http://mrdoob.com/
  13896. */
  13897. function Group() {
  13898. Object3D.call( this );
  13899. this.type = 'Group';
  13900. }
  13901. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13902. constructor: Group
  13903. } );
  13904. /**
  13905. * @author mrdoob / http://mrdoob.com/
  13906. */
  13907. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13908. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13909. this.generateMipmaps = false;
  13910. var scope = this;
  13911. function update() {
  13912. requestAnimationFrame( update );
  13913. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13914. scope.needsUpdate = true;
  13915. }
  13916. }
  13917. update();
  13918. }
  13919. VideoTexture.prototype = Object.create( Texture.prototype );
  13920. VideoTexture.prototype.constructor = VideoTexture;
  13921. /**
  13922. * @author alteredq / http://alteredqualia.com/
  13923. */
  13924. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13925. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13926. this.image = { width: width, height: height };
  13927. this.mipmaps = mipmaps;
  13928. // no flipping for cube textures
  13929. // (also flipping doesn't work for compressed textures )
  13930. this.flipY = false;
  13931. // can't generate mipmaps for compressed textures
  13932. // mips must be embedded in DDS files
  13933. this.generateMipmaps = false;
  13934. }
  13935. CompressedTexture.prototype = Object.create( Texture.prototype );
  13936. CompressedTexture.prototype.constructor = CompressedTexture;
  13937. CompressedTexture.prototype.isCompressedTexture = true;
  13938. /**
  13939. * @author mrdoob / http://mrdoob.com/
  13940. */
  13941. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13942. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13943. this.needsUpdate = true;
  13944. }
  13945. CanvasTexture.prototype = Object.create( Texture.prototype );
  13946. CanvasTexture.prototype.constructor = CanvasTexture;
  13947. /**
  13948. * @author Matt DesLauriers / @mattdesl
  13949. * @author atix / arthursilber.de
  13950. */
  13951. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  13952. format = format !== undefined ? format : DepthFormat;
  13953. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  13954. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  13955. }
  13956. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13957. this.image = { width: width, height: height };
  13958. this.type = type !== undefined ? type : UnsignedShortType;
  13959. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13960. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13961. this.flipY = false;
  13962. this.generateMipmaps = false;
  13963. }
  13964. DepthTexture.prototype = Object.create( Texture.prototype );
  13965. DepthTexture.prototype.constructor = DepthTexture;
  13966. DepthTexture.prototype.isDepthTexture = true;
  13967. /**
  13968. * @author mrdoob / http://mrdoob.com/
  13969. */
  13970. function ShadowMaterial() {
  13971. ShaderMaterial.call( this, {
  13972. uniforms: exports.UniformsUtils.merge( [
  13973. UniformsLib[ "lights" ],
  13974. {
  13975. opacity: { value: 1.0 }
  13976. }
  13977. ] ),
  13978. vertexShader: ShaderChunk[ 'shadow_vert' ],
  13979. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  13980. } );
  13981. this.lights = true;
  13982. this.transparent = true;
  13983. Object.defineProperties( this, {
  13984. opacity: {
  13985. enumerable: true,
  13986. get: function () {
  13987. return this.uniforms.opacity.value;
  13988. },
  13989. set: function ( value ) {
  13990. this.uniforms.opacity.value = value;
  13991. }
  13992. }
  13993. } );
  13994. }
  13995. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  13996. ShadowMaterial.prototype.constructor = ShadowMaterial;
  13997. ShadowMaterial.prototype.isShadowMaterial = true;
  13998. /**
  13999. * @author mrdoob / http://mrdoob.com/
  14000. */
  14001. function RawShaderMaterial( parameters ) {
  14002. ShaderMaterial.call( this, parameters );
  14003. this.type = 'RawShaderMaterial';
  14004. }
  14005. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  14006. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  14007. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  14008. /**
  14009. * @author mrdoob / http://mrdoob.com/
  14010. */
  14011. function MultiMaterial( materials ) {
  14012. this.uuid = exports.Math.generateUUID();
  14013. this.type = 'MultiMaterial';
  14014. this.materials = materials instanceof Array ? materials : [];
  14015. this.visible = true;
  14016. }
  14017. MultiMaterial.prototype = {
  14018. constructor: MultiMaterial,
  14019. isMultiMaterial: true,
  14020. toJSON: function ( meta ) {
  14021. var output = {
  14022. metadata: {
  14023. version: 4.2,
  14024. type: 'material',
  14025. generator: 'MaterialExporter'
  14026. },
  14027. uuid: this.uuid,
  14028. type: this.type,
  14029. materials: []
  14030. };
  14031. var materials = this.materials;
  14032. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14033. var material = materials[ i ].toJSON( meta );
  14034. delete material.metadata;
  14035. output.materials.push( material );
  14036. }
  14037. output.visible = this.visible;
  14038. return output;
  14039. },
  14040. clone: function () {
  14041. var material = new this.constructor();
  14042. for ( var i = 0; i < this.materials.length; i ++ ) {
  14043. material.materials.push( this.materials[ i ].clone() );
  14044. }
  14045. material.visible = this.visible;
  14046. return material;
  14047. }
  14048. };
  14049. /**
  14050. * @author WestLangley / http://github.com/WestLangley
  14051. *
  14052. * parameters = {
  14053. * color: <hex>,
  14054. * roughness: <float>,
  14055. * metalness: <float>,
  14056. * opacity: <float>,
  14057. *
  14058. * map: new THREE.Texture( <Image> ),
  14059. *
  14060. * lightMap: new THREE.Texture( <Image> ),
  14061. * lightMapIntensity: <float>
  14062. *
  14063. * aoMap: new THREE.Texture( <Image> ),
  14064. * aoMapIntensity: <float>
  14065. *
  14066. * emissive: <hex>,
  14067. * emissiveIntensity: <float>
  14068. * emissiveMap: new THREE.Texture( <Image> ),
  14069. *
  14070. * bumpMap: new THREE.Texture( <Image> ),
  14071. * bumpScale: <float>,
  14072. *
  14073. * normalMap: new THREE.Texture( <Image> ),
  14074. * normalScale: <Vector2>,
  14075. *
  14076. * displacementMap: new THREE.Texture( <Image> ),
  14077. * displacementScale: <float>,
  14078. * displacementBias: <float>,
  14079. *
  14080. * roughnessMap: new THREE.Texture( <Image> ),
  14081. *
  14082. * metalnessMap: new THREE.Texture( <Image> ),
  14083. *
  14084. * alphaMap: new THREE.Texture( <Image> ),
  14085. *
  14086. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  14087. * envMapIntensity: <float>
  14088. *
  14089. * refractionRatio: <float>,
  14090. *
  14091. * wireframe: <boolean>,
  14092. * wireframeLinewidth: <float>,
  14093. *
  14094. * skinning: <bool>,
  14095. * morphTargets: <bool>,
  14096. * morphNormals: <bool>
  14097. * }
  14098. */
  14099. function MeshStandardMaterial( parameters ) {
  14100. Material.call( this );
  14101. this.defines = { 'STANDARD': '' };
  14102. this.type = 'MeshStandardMaterial';
  14103. this.color = new Color( 0xffffff ); // diffuse
  14104. this.roughness = 0.5;
  14105. this.metalness = 0.5;
  14106. this.map = null;
  14107. this.lightMap = null;
  14108. this.lightMapIntensity = 1.0;
  14109. this.aoMap = null;
  14110. this.aoMapIntensity = 1.0;
  14111. this.emissive = new Color( 0x000000 );
  14112. this.emissiveIntensity = 1.0;
  14113. this.emissiveMap = null;
  14114. this.bumpMap = null;
  14115. this.bumpScale = 1;
  14116. this.normalMap = null;
  14117. this.normalScale = new Vector2( 1, 1 );
  14118. this.displacementMap = null;
  14119. this.displacementScale = 1;
  14120. this.displacementBias = 0;
  14121. this.roughnessMap = null;
  14122. this.metalnessMap = null;
  14123. this.alphaMap = null;
  14124. this.envMap = null;
  14125. this.envMapIntensity = 1.0;
  14126. this.refractionRatio = 0.98;
  14127. this.wireframe = false;
  14128. this.wireframeLinewidth = 1;
  14129. this.wireframeLinecap = 'round';
  14130. this.wireframeLinejoin = 'round';
  14131. this.skinning = false;
  14132. this.morphTargets = false;
  14133. this.morphNormals = false;
  14134. this.setValues( parameters );
  14135. }
  14136. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  14137. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  14138. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  14139. MeshStandardMaterial.prototype.copy = function ( source ) {
  14140. Material.prototype.copy.call( this, source );
  14141. this.defines = { 'STANDARD': '' };
  14142. this.color.copy( source.color );
  14143. this.roughness = source.roughness;
  14144. this.metalness = source.metalness;
  14145. this.map = source.map;
  14146. this.lightMap = source.lightMap;
  14147. this.lightMapIntensity = source.lightMapIntensity;
  14148. this.aoMap = source.aoMap;
  14149. this.aoMapIntensity = source.aoMapIntensity;
  14150. this.emissive.copy( source.emissive );
  14151. this.emissiveMap = source.emissiveMap;
  14152. this.emissiveIntensity = source.emissiveIntensity;
  14153. this.bumpMap = source.bumpMap;
  14154. this.bumpScale = source.bumpScale;
  14155. this.normalMap = source.normalMap;
  14156. this.normalScale.copy( source.normalScale );
  14157. this.displacementMap = source.displacementMap;
  14158. this.displacementScale = source.displacementScale;
  14159. this.displacementBias = source.displacementBias;
  14160. this.roughnessMap = source.roughnessMap;
  14161. this.metalnessMap = source.metalnessMap;
  14162. this.alphaMap = source.alphaMap;
  14163. this.envMap = source.envMap;
  14164. this.envMapIntensity = source.envMapIntensity;
  14165. this.refractionRatio = source.refractionRatio;
  14166. this.wireframe = source.wireframe;
  14167. this.wireframeLinewidth = source.wireframeLinewidth;
  14168. this.wireframeLinecap = source.wireframeLinecap;
  14169. this.wireframeLinejoin = source.wireframeLinejoin;
  14170. this.skinning = source.skinning;
  14171. this.morphTargets = source.morphTargets;
  14172. this.morphNormals = source.morphNormals;
  14173. return this;
  14174. };
  14175. /**
  14176. * @author WestLangley / http://github.com/WestLangley
  14177. *
  14178. * parameters = {
  14179. * reflectivity: <float>
  14180. * }
  14181. */
  14182. function MeshPhysicalMaterial( parameters ) {
  14183. MeshStandardMaterial.call( this );
  14184. this.defines = { 'PHYSICAL': '' };
  14185. this.type = 'MeshPhysicalMaterial';
  14186. this.reflectivity = 0.5; // maps to F0 = 0.04
  14187. this.clearCoat = 0.0;
  14188. this.clearCoatRoughness = 0.0;
  14189. this.setValues( parameters );
  14190. }
  14191. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  14192. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  14193. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  14194. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  14195. MeshStandardMaterial.prototype.copy.call( this, source );
  14196. this.defines = { 'PHYSICAL': '' };
  14197. this.reflectivity = source.reflectivity;
  14198. this.clearCoat = source.clearCoat;
  14199. this.clearCoatRoughness = source.clearCoatRoughness;
  14200. return this;
  14201. };
  14202. /**
  14203. * @author mrdoob / http://mrdoob.com/
  14204. * @author alteredq / http://alteredqualia.com/
  14205. *
  14206. * parameters = {
  14207. * color: <hex>,
  14208. * specular: <hex>,
  14209. * shininess: <float>,
  14210. * opacity: <float>,
  14211. *
  14212. * map: new THREE.Texture( <Image> ),
  14213. *
  14214. * lightMap: new THREE.Texture( <Image> ),
  14215. * lightMapIntensity: <float>
  14216. *
  14217. * aoMap: new THREE.Texture( <Image> ),
  14218. * aoMapIntensity: <float>
  14219. *
  14220. * emissive: <hex>,
  14221. * emissiveIntensity: <float>
  14222. * emissiveMap: new THREE.Texture( <Image> ),
  14223. *
  14224. * bumpMap: new THREE.Texture( <Image> ),
  14225. * bumpScale: <float>,
  14226. *
  14227. * normalMap: new THREE.Texture( <Image> ),
  14228. * normalScale: <Vector2>,
  14229. *
  14230. * displacementMap: new THREE.Texture( <Image> ),
  14231. * displacementScale: <float>,
  14232. * displacementBias: <float>,
  14233. *
  14234. * specularMap: new THREE.Texture( <Image> ),
  14235. *
  14236. * alphaMap: new THREE.Texture( <Image> ),
  14237. *
  14238. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14239. * combine: THREE.Multiply,
  14240. * reflectivity: <float>,
  14241. * refractionRatio: <float>,
  14242. *
  14243. * wireframe: <boolean>,
  14244. * wireframeLinewidth: <float>,
  14245. *
  14246. * skinning: <bool>,
  14247. * morphTargets: <bool>,
  14248. * morphNormals: <bool>
  14249. * }
  14250. */
  14251. function MeshPhongMaterial( parameters ) {
  14252. Material.call( this );
  14253. this.type = 'MeshPhongMaterial';
  14254. this.color = new Color( 0xffffff ); // diffuse
  14255. this.specular = new Color( 0x111111 );
  14256. this.shininess = 30;
  14257. this.map = null;
  14258. this.lightMap = null;
  14259. this.lightMapIntensity = 1.0;
  14260. this.aoMap = null;
  14261. this.aoMapIntensity = 1.0;
  14262. this.emissive = new Color( 0x000000 );
  14263. this.emissiveIntensity = 1.0;
  14264. this.emissiveMap = null;
  14265. this.bumpMap = null;
  14266. this.bumpScale = 1;
  14267. this.normalMap = null;
  14268. this.normalScale = new Vector2( 1, 1 );
  14269. this.displacementMap = null;
  14270. this.displacementScale = 1;
  14271. this.displacementBias = 0;
  14272. this.specularMap = null;
  14273. this.alphaMap = null;
  14274. this.envMap = null;
  14275. this.combine = MultiplyOperation;
  14276. this.reflectivity = 1;
  14277. this.refractionRatio = 0.98;
  14278. this.wireframe = false;
  14279. this.wireframeLinewidth = 1;
  14280. this.wireframeLinecap = 'round';
  14281. this.wireframeLinejoin = 'round';
  14282. this.skinning = false;
  14283. this.morphTargets = false;
  14284. this.morphNormals = false;
  14285. this.setValues( parameters );
  14286. }
  14287. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  14288. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  14289. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  14290. MeshPhongMaterial.prototype.copy = function ( source ) {
  14291. Material.prototype.copy.call( this, source );
  14292. this.color.copy( source.color );
  14293. this.specular.copy( source.specular );
  14294. this.shininess = source.shininess;
  14295. this.map = source.map;
  14296. this.lightMap = source.lightMap;
  14297. this.lightMapIntensity = source.lightMapIntensity;
  14298. this.aoMap = source.aoMap;
  14299. this.aoMapIntensity = source.aoMapIntensity;
  14300. this.emissive.copy( source.emissive );
  14301. this.emissiveMap = source.emissiveMap;
  14302. this.emissiveIntensity = source.emissiveIntensity;
  14303. this.bumpMap = source.bumpMap;
  14304. this.bumpScale = source.bumpScale;
  14305. this.normalMap = source.normalMap;
  14306. this.normalScale.copy( source.normalScale );
  14307. this.displacementMap = source.displacementMap;
  14308. this.displacementScale = source.displacementScale;
  14309. this.displacementBias = source.displacementBias;
  14310. this.specularMap = source.specularMap;
  14311. this.alphaMap = source.alphaMap;
  14312. this.envMap = source.envMap;
  14313. this.combine = source.combine;
  14314. this.reflectivity = source.reflectivity;
  14315. this.refractionRatio = source.refractionRatio;
  14316. this.wireframe = source.wireframe;
  14317. this.wireframeLinewidth = source.wireframeLinewidth;
  14318. this.wireframeLinecap = source.wireframeLinecap;
  14319. this.wireframeLinejoin = source.wireframeLinejoin;
  14320. this.skinning = source.skinning;
  14321. this.morphTargets = source.morphTargets;
  14322. this.morphNormals = source.morphNormals;
  14323. return this;
  14324. };
  14325. /**
  14326. * @author mrdoob / http://mrdoob.com/
  14327. *
  14328. * parameters = {
  14329. * opacity: <float>,
  14330. *
  14331. * wireframe: <boolean>,
  14332. * wireframeLinewidth: <float>
  14333. * }
  14334. */
  14335. function MeshNormalMaterial( parameters ) {
  14336. Material.call( this, parameters );
  14337. this.type = 'MeshNormalMaterial';
  14338. this.wireframe = false;
  14339. this.wireframeLinewidth = 1;
  14340. this.fog = false;
  14341. this.lights = false;
  14342. this.morphTargets = false;
  14343. this.setValues( parameters );
  14344. }
  14345. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  14346. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  14347. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  14348. MeshNormalMaterial.prototype.copy = function ( source ) {
  14349. Material.prototype.copy.call( this, source );
  14350. this.wireframe = source.wireframe;
  14351. this.wireframeLinewidth = source.wireframeLinewidth;
  14352. return this;
  14353. };
  14354. /**
  14355. * @author mrdoob / http://mrdoob.com/
  14356. * @author alteredq / http://alteredqualia.com/
  14357. *
  14358. * parameters = {
  14359. * color: <hex>,
  14360. * opacity: <float>,
  14361. *
  14362. * map: new THREE.Texture( <Image> ),
  14363. *
  14364. * lightMap: new THREE.Texture( <Image> ),
  14365. * lightMapIntensity: <float>
  14366. *
  14367. * aoMap: new THREE.Texture( <Image> ),
  14368. * aoMapIntensity: <float>
  14369. *
  14370. * emissive: <hex>,
  14371. * emissiveIntensity: <float>
  14372. * emissiveMap: new THREE.Texture( <Image> ),
  14373. *
  14374. * specularMap: new THREE.Texture( <Image> ),
  14375. *
  14376. * alphaMap: new THREE.Texture( <Image> ),
  14377. *
  14378. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14379. * combine: THREE.Multiply,
  14380. * reflectivity: <float>,
  14381. * refractionRatio: <float>,
  14382. *
  14383. * wireframe: <boolean>,
  14384. * wireframeLinewidth: <float>,
  14385. *
  14386. * skinning: <bool>,
  14387. * morphTargets: <bool>,
  14388. * morphNormals: <bool>
  14389. * }
  14390. */
  14391. function MeshLambertMaterial( parameters ) {
  14392. Material.call( this );
  14393. this.type = 'MeshLambertMaterial';
  14394. this.color = new Color( 0xffffff ); // diffuse
  14395. this.map = null;
  14396. this.lightMap = null;
  14397. this.lightMapIntensity = 1.0;
  14398. this.aoMap = null;
  14399. this.aoMapIntensity = 1.0;
  14400. this.emissive = new Color( 0x000000 );
  14401. this.emissiveIntensity = 1.0;
  14402. this.emissiveMap = null;
  14403. this.specularMap = null;
  14404. this.alphaMap = null;
  14405. this.envMap = null;
  14406. this.combine = MultiplyOperation;
  14407. this.reflectivity = 1;
  14408. this.refractionRatio = 0.98;
  14409. this.wireframe = false;
  14410. this.wireframeLinewidth = 1;
  14411. this.wireframeLinecap = 'round';
  14412. this.wireframeLinejoin = 'round';
  14413. this.skinning = false;
  14414. this.morphTargets = false;
  14415. this.morphNormals = false;
  14416. this.setValues( parameters );
  14417. }
  14418. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  14419. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  14420. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  14421. MeshLambertMaterial.prototype.copy = function ( source ) {
  14422. Material.prototype.copy.call( this, source );
  14423. this.color.copy( source.color );
  14424. this.map = source.map;
  14425. this.lightMap = source.lightMap;
  14426. this.lightMapIntensity = source.lightMapIntensity;
  14427. this.aoMap = source.aoMap;
  14428. this.aoMapIntensity = source.aoMapIntensity;
  14429. this.emissive.copy( source.emissive );
  14430. this.emissiveMap = source.emissiveMap;
  14431. this.emissiveIntensity = source.emissiveIntensity;
  14432. this.specularMap = source.specularMap;
  14433. this.alphaMap = source.alphaMap;
  14434. this.envMap = source.envMap;
  14435. this.combine = source.combine;
  14436. this.reflectivity = source.reflectivity;
  14437. this.refractionRatio = source.refractionRatio;
  14438. this.wireframe = source.wireframe;
  14439. this.wireframeLinewidth = source.wireframeLinewidth;
  14440. this.wireframeLinecap = source.wireframeLinecap;
  14441. this.wireframeLinejoin = source.wireframeLinejoin;
  14442. this.skinning = source.skinning;
  14443. this.morphTargets = source.morphTargets;
  14444. this.morphNormals = source.morphNormals;
  14445. return this;
  14446. };
  14447. /**
  14448. * @author alteredq / http://alteredqualia.com/
  14449. *
  14450. * parameters = {
  14451. * color: <hex>,
  14452. * opacity: <float>,
  14453. *
  14454. * linewidth: <float>,
  14455. *
  14456. * scale: <float>,
  14457. * dashSize: <float>,
  14458. * gapSize: <float>
  14459. * }
  14460. */
  14461. function LineDashedMaterial( parameters ) {
  14462. Material.call( this );
  14463. this.type = 'LineDashedMaterial';
  14464. this.color = new Color( 0xffffff );
  14465. this.linewidth = 1;
  14466. this.scale = 1;
  14467. this.dashSize = 3;
  14468. this.gapSize = 1;
  14469. this.lights = false;
  14470. this.setValues( parameters );
  14471. }
  14472. LineDashedMaterial.prototype = Object.create( Material.prototype );
  14473. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  14474. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  14475. LineDashedMaterial.prototype.copy = function ( source ) {
  14476. Material.prototype.copy.call( this, source );
  14477. this.color.copy( source.color );
  14478. this.linewidth = source.linewidth;
  14479. this.scale = source.scale;
  14480. this.dashSize = source.dashSize;
  14481. this.gapSize = source.gapSize;
  14482. return this;
  14483. };
  14484. /**
  14485. * @author mrdoob / http://mrdoob.com/
  14486. */
  14487. exports.Cache = {
  14488. enabled: false,
  14489. files: {},
  14490. add: function ( key, file ) {
  14491. if ( this.enabled === false ) return;
  14492. // console.log( 'THREE.Cache', 'Adding key:', key );
  14493. this.files[ key ] = file;
  14494. },
  14495. get: function ( key ) {
  14496. if ( this.enabled === false ) return;
  14497. // console.log( 'THREE.Cache', 'Checking key:', key );
  14498. return this.files[ key ];
  14499. },
  14500. remove: function ( key ) {
  14501. delete this.files[ key ];
  14502. },
  14503. clear: function () {
  14504. this.files = {};
  14505. }
  14506. };
  14507. /**
  14508. * @author mrdoob / http://mrdoob.com/
  14509. */
  14510. function LoadingManager( onLoad, onProgress, onError ) {
  14511. var scope = this;
  14512. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  14513. this.onStart = undefined;
  14514. this.onLoad = onLoad;
  14515. this.onProgress = onProgress;
  14516. this.onError = onError;
  14517. this.itemStart = function ( url ) {
  14518. itemsTotal ++;
  14519. if ( isLoading === false ) {
  14520. if ( scope.onStart !== undefined ) {
  14521. scope.onStart( url, itemsLoaded, itemsTotal );
  14522. }
  14523. }
  14524. isLoading = true;
  14525. };
  14526. this.itemEnd = function ( url ) {
  14527. itemsLoaded ++;
  14528. if ( scope.onProgress !== undefined ) {
  14529. scope.onProgress( url, itemsLoaded, itemsTotal );
  14530. }
  14531. if ( itemsLoaded === itemsTotal ) {
  14532. isLoading = false;
  14533. if ( scope.onLoad !== undefined ) {
  14534. scope.onLoad();
  14535. }
  14536. }
  14537. };
  14538. this.itemError = function ( url ) {
  14539. if ( scope.onError !== undefined ) {
  14540. scope.onError( url );
  14541. }
  14542. };
  14543. }
  14544. exports.DefaultLoadingManager = new LoadingManager();
  14545. /**
  14546. * @author mrdoob / http://mrdoob.com/
  14547. */
  14548. function XHRLoader( manager ) {
  14549. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14550. }
  14551. Object.assign( XHRLoader.prototype, {
  14552. load: function ( url, onLoad, onProgress, onError ) {
  14553. if ( this.path !== undefined ) url = this.path + url;
  14554. var scope = this;
  14555. var cached = exports.Cache.get( url );
  14556. if ( cached !== undefined ) {
  14557. scope.manager.itemStart( url );
  14558. setTimeout( function () {
  14559. if ( onLoad ) onLoad( cached );
  14560. scope.manager.itemEnd( url );
  14561. }, 0 );
  14562. return cached;
  14563. }
  14564. var request = new XMLHttpRequest();
  14565. request.open( 'GET', url, true );
  14566. request.addEventListener( 'load', function ( event ) {
  14567. var response = event.target.response;
  14568. exports.Cache.add( url, response );
  14569. if ( this.status === 200 ) {
  14570. if ( onLoad ) onLoad( response );
  14571. scope.manager.itemEnd( url );
  14572. } else if ( this.status === 0 ) {
  14573. // Some browsers return HTTP Status 0 when using non-http protocol
  14574. // e.g. 'file://' or 'data://'. Handle as success.
  14575. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  14576. if ( onLoad ) onLoad( response );
  14577. scope.manager.itemEnd( url );
  14578. } else {
  14579. if ( onError ) onError( event );
  14580. scope.manager.itemError( url );
  14581. }
  14582. }, false );
  14583. if ( onProgress !== undefined ) {
  14584. request.addEventListener( 'progress', function ( event ) {
  14585. onProgress( event );
  14586. }, false );
  14587. }
  14588. request.addEventListener( 'error', function ( event ) {
  14589. if ( onError ) onError( event );
  14590. scope.manager.itemError( url );
  14591. }, false );
  14592. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  14593. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  14594. if ( request.overrideMimeType ) request.overrideMimeType( 'text/plain' );
  14595. request.send( null );
  14596. scope.manager.itemStart( url );
  14597. return request;
  14598. },
  14599. setPath: function ( value ) {
  14600. this.path = value;
  14601. return this;
  14602. },
  14603. setResponseType: function ( value ) {
  14604. this.responseType = value;
  14605. return this;
  14606. },
  14607. setWithCredentials: function ( value ) {
  14608. this.withCredentials = value;
  14609. return this;
  14610. }
  14611. } );
  14612. /**
  14613. * @author mrdoob / http://mrdoob.com/
  14614. *
  14615. * Abstract Base class to block based textures loader (dds, pvr, ...)
  14616. */
  14617. function CompressedTextureLoader( manager ) {
  14618. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14619. // override in sub classes
  14620. this._parser = null;
  14621. }
  14622. Object.assign( CompressedTextureLoader.prototype, {
  14623. load: function ( url, onLoad, onProgress, onError ) {
  14624. var scope = this;
  14625. var images = [];
  14626. var texture = new CompressedTexture();
  14627. texture.image = images;
  14628. var loader = new XHRLoader( this.manager );
  14629. loader.setPath( this.path );
  14630. loader.setResponseType( 'arraybuffer' );
  14631. function loadTexture( i ) {
  14632. loader.load( url[ i ], function ( buffer ) {
  14633. var texDatas = scope._parser( buffer, true );
  14634. images[ i ] = {
  14635. width: texDatas.width,
  14636. height: texDatas.height,
  14637. format: texDatas.format,
  14638. mipmaps: texDatas.mipmaps
  14639. };
  14640. loaded += 1;
  14641. if ( loaded === 6 ) {
  14642. if ( texDatas.mipmapCount === 1 )
  14643. texture.minFilter = LinearFilter;
  14644. texture.format = texDatas.format;
  14645. texture.needsUpdate = true;
  14646. if ( onLoad ) onLoad( texture );
  14647. }
  14648. }, onProgress, onError );
  14649. }
  14650. if ( Array.isArray( url ) ) {
  14651. var loaded = 0;
  14652. for ( var i = 0, il = url.length; i < il; ++ i ) {
  14653. loadTexture( i );
  14654. }
  14655. } else {
  14656. // compressed cubemap texture stored in a single DDS file
  14657. loader.load( url, function ( buffer ) {
  14658. var texDatas = scope._parser( buffer, true );
  14659. if ( texDatas.isCubemap ) {
  14660. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  14661. for ( var f = 0; f < faces; f ++ ) {
  14662. images[ f ] = { mipmaps : [] };
  14663. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  14664. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  14665. images[ f ].format = texDatas.format;
  14666. images[ f ].width = texDatas.width;
  14667. images[ f ].height = texDatas.height;
  14668. }
  14669. }
  14670. } else {
  14671. texture.image.width = texDatas.width;
  14672. texture.image.height = texDatas.height;
  14673. texture.mipmaps = texDatas.mipmaps;
  14674. }
  14675. if ( texDatas.mipmapCount === 1 ) {
  14676. texture.minFilter = LinearFilter;
  14677. }
  14678. texture.format = texDatas.format;
  14679. texture.needsUpdate = true;
  14680. if ( onLoad ) onLoad( texture );
  14681. }, onProgress, onError );
  14682. }
  14683. return texture;
  14684. },
  14685. setPath: function ( value ) {
  14686. this.path = value;
  14687. return this;
  14688. }
  14689. } );
  14690. /**
  14691. * @author Nikos M. / https://github.com/foo123/
  14692. *
  14693. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  14694. */
  14695. var DataTextureLoader = BinaryTextureLoader;
  14696. function BinaryTextureLoader( manager ) {
  14697. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14698. // override in sub classes
  14699. this._parser = null;
  14700. }
  14701. Object.assign( BinaryTextureLoader.prototype, {
  14702. load: function ( url, onLoad, onProgress, onError ) {
  14703. var scope = this;
  14704. var texture = new DataTexture();
  14705. var loader = new XHRLoader( this.manager );
  14706. loader.setResponseType( 'arraybuffer' );
  14707. loader.load( url, function ( buffer ) {
  14708. var texData = scope._parser( buffer );
  14709. if ( ! texData ) return;
  14710. if ( undefined !== texData.image ) {
  14711. texture.image = texData.image;
  14712. } else if ( undefined !== texData.data ) {
  14713. texture.image.width = texData.width;
  14714. texture.image.height = texData.height;
  14715. texture.image.data = texData.data;
  14716. }
  14717. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  14718. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  14719. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  14720. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  14721. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  14722. if ( undefined !== texData.format ) {
  14723. texture.format = texData.format;
  14724. }
  14725. if ( undefined !== texData.type ) {
  14726. texture.type = texData.type;
  14727. }
  14728. if ( undefined !== texData.mipmaps ) {
  14729. texture.mipmaps = texData.mipmaps;
  14730. }
  14731. if ( 1 === texData.mipmapCount ) {
  14732. texture.minFilter = LinearFilter;
  14733. }
  14734. texture.needsUpdate = true;
  14735. if ( onLoad ) onLoad( texture, texData );
  14736. }, onProgress, onError );
  14737. return texture;
  14738. }
  14739. } );
  14740. /**
  14741. * @author mrdoob / http://mrdoob.com/
  14742. */
  14743. function ImageLoader( manager ) {
  14744. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14745. }
  14746. Object.assign( ImageLoader.prototype, {
  14747. load: function ( url, onLoad, onProgress, onError ) {
  14748. var scope = this;
  14749. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  14750. image.onload = function () {
  14751. URL.revokeObjectURL( image.src );
  14752. if ( onLoad ) onLoad( image );
  14753. scope.manager.itemEnd( url );
  14754. };
  14755. if ( url.indexOf( 'data:' ) === 0 ) {
  14756. image.src = url;
  14757. } else {
  14758. var loader = new XHRLoader();
  14759. loader.setPath( this.path );
  14760. loader.setResponseType( 'blob' );
  14761. loader.setWithCredentials( this.withCredentials );
  14762. loader.load( url, function ( blob ) {
  14763. image.src = URL.createObjectURL( blob );
  14764. }, onProgress, onError );
  14765. }
  14766. scope.manager.itemStart( url );
  14767. return image;
  14768. },
  14769. setCrossOrigin: function ( value ) {
  14770. this.crossOrigin = value;
  14771. return this;
  14772. },
  14773. setWithCredentials: function ( value ) {
  14774. this.withCredentials = value;
  14775. return this;
  14776. },
  14777. setPath: function ( value ) {
  14778. this.path = value;
  14779. return this;
  14780. }
  14781. } );
  14782. /**
  14783. * @author mrdoob / http://mrdoob.com/
  14784. */
  14785. function CubeTextureLoader( manager ) {
  14786. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14787. }
  14788. Object.assign( CubeTextureLoader.prototype, {
  14789. load: function ( urls, onLoad, onProgress, onError ) {
  14790. var texture = new CubeTexture();
  14791. var loader = new ImageLoader( this.manager );
  14792. loader.setCrossOrigin( this.crossOrigin );
  14793. loader.setPath( this.path );
  14794. var loaded = 0;
  14795. function loadTexture( i ) {
  14796. loader.load( urls[ i ], function ( image ) {
  14797. texture.images[ i ] = image;
  14798. loaded ++;
  14799. if ( loaded === 6 ) {
  14800. texture.needsUpdate = true;
  14801. if ( onLoad ) onLoad( texture );
  14802. }
  14803. }, undefined, onError );
  14804. }
  14805. for ( var i = 0; i < urls.length; ++ i ) {
  14806. loadTexture( i );
  14807. }
  14808. return texture;
  14809. },
  14810. setCrossOrigin: function ( value ) {
  14811. this.crossOrigin = value;
  14812. return this;
  14813. },
  14814. setPath: function ( value ) {
  14815. this.path = value;
  14816. return this;
  14817. }
  14818. } );
  14819. /**
  14820. * @author mrdoob / http://mrdoob.com/
  14821. */
  14822. function TextureLoader( manager ) {
  14823. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14824. }
  14825. Object.assign( TextureLoader.prototype, {
  14826. load: function ( url, onLoad, onProgress, onError ) {
  14827. var texture = new Texture();
  14828. var loader = new ImageLoader( this.manager );
  14829. loader.setCrossOrigin( this.crossOrigin );
  14830. loader.setWithCredentials( this.withCredentials );
  14831. loader.setPath( this.path );
  14832. loader.load( url, function ( image ) {
  14833. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  14834. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  14835. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  14836. texture.image = image;
  14837. texture.needsUpdate = true;
  14838. if ( onLoad !== undefined ) {
  14839. onLoad( texture );
  14840. }
  14841. }, onProgress, onError );
  14842. return texture;
  14843. },
  14844. setCrossOrigin: function ( value ) {
  14845. this.crossOrigin = value;
  14846. return this;
  14847. },
  14848. setWithCredentials: function ( value ) {
  14849. this.withCredentials = value;
  14850. return this;
  14851. },
  14852. setPath: function ( value ) {
  14853. this.path = value;
  14854. return this;
  14855. }
  14856. } );
  14857. /**
  14858. * @author mrdoob / http://mrdoob.com/
  14859. * @author alteredq / http://alteredqualia.com/
  14860. */
  14861. function Light( color, intensity ) {
  14862. Object3D.call( this );
  14863. this.type = 'Light';
  14864. this.color = new Color( color );
  14865. this.intensity = intensity !== undefined ? intensity : 1;
  14866. this.receiveShadow = undefined;
  14867. }
  14868. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14869. constructor: Light,
  14870. isLight: true,
  14871. copy: function ( source ) {
  14872. Object3D.prototype.copy.call( this, source );
  14873. this.color.copy( source.color );
  14874. this.intensity = source.intensity;
  14875. return this;
  14876. },
  14877. toJSON: function ( meta ) {
  14878. var data = Object3D.prototype.toJSON.call( this, meta );
  14879. data.object.color = this.color.getHex();
  14880. data.object.intensity = this.intensity;
  14881. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  14882. if ( this.distance !== undefined ) data.object.distance = this.distance;
  14883. if ( this.angle !== undefined ) data.object.angle = this.angle;
  14884. if ( this.decay !== undefined ) data.object.decay = this.decay;
  14885. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  14886. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  14887. return data;
  14888. }
  14889. } );
  14890. /**
  14891. * @author alteredq / http://alteredqualia.com/
  14892. */
  14893. function HemisphereLight( skyColor, groundColor, intensity ) {
  14894. Light.call( this, skyColor, intensity );
  14895. this.type = 'HemisphereLight';
  14896. this.castShadow = undefined;
  14897. this.position.copy( Object3D.DefaultUp );
  14898. this.updateMatrix();
  14899. this.groundColor = new Color( groundColor );
  14900. }
  14901. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14902. constructor: HemisphereLight,
  14903. isHemisphereLight: true,
  14904. copy: function ( source ) {
  14905. Light.prototype.copy.call( this, source );
  14906. this.groundColor.copy( source.groundColor );
  14907. return this;
  14908. }
  14909. } );
  14910. /**
  14911. * @author mrdoob / http://mrdoob.com/
  14912. */
  14913. function LightShadow( camera ) {
  14914. this.camera = camera;
  14915. this.bias = 0;
  14916. this.radius = 1;
  14917. this.mapSize = new Vector2( 512, 512 );
  14918. this.map = null;
  14919. this.matrix = new Matrix4();
  14920. }
  14921. Object.assign( LightShadow.prototype, {
  14922. copy: function ( source ) {
  14923. this.camera = source.camera.clone();
  14924. this.bias = source.bias;
  14925. this.radius = source.radius;
  14926. this.mapSize.copy( source.mapSize );
  14927. return this;
  14928. },
  14929. clone: function () {
  14930. return new this.constructor().copy( this );
  14931. },
  14932. toJSON: function () {
  14933. var object = {};
  14934. if ( this.bias !== 0 ) object.bias = this.bias;
  14935. if ( this.radius !== 1 ) object.radius = this.radius;
  14936. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  14937. object.camera = this.camera.toJSON( false ).object;
  14938. delete object.camera.matrix;
  14939. return object;
  14940. }
  14941. } );
  14942. /**
  14943. * @author mrdoob / http://mrdoob.com/
  14944. */
  14945. function SpotLightShadow() {
  14946. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  14947. }
  14948. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  14949. constructor: SpotLightShadow,
  14950. isSpotLightShadow: true,
  14951. update: function ( light ) {
  14952. var fov = exports.Math.RAD2DEG * 2 * light.angle;
  14953. var aspect = this.mapSize.width / this.mapSize.height;
  14954. var far = light.distance || 500;
  14955. var camera = this.camera;
  14956. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  14957. camera.fov = fov;
  14958. camera.aspect = aspect;
  14959. camera.far = far;
  14960. camera.updateProjectionMatrix();
  14961. }
  14962. }
  14963. } );
  14964. /**
  14965. * @author alteredq / http://alteredqualia.com/
  14966. */
  14967. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  14968. Light.call( this, color, intensity );
  14969. this.type = 'SpotLight';
  14970. this.position.copy( Object3D.DefaultUp );
  14971. this.updateMatrix();
  14972. this.target = new Object3D();
  14973. Object.defineProperty( this, 'power', {
  14974. get: function () {
  14975. // intensity = power per solid angle.
  14976. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14977. return this.intensity * Math.PI;
  14978. },
  14979. set: function ( power ) {
  14980. // intensity = power per solid angle.
  14981. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14982. this.intensity = power / Math.PI;
  14983. }
  14984. } );
  14985. this.distance = ( distance !== undefined ) ? distance : 0;
  14986. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  14987. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  14988. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  14989. this.shadow = new SpotLightShadow();
  14990. }
  14991. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14992. constructor: SpotLight,
  14993. isSpotLight: true,
  14994. copy: function ( source ) {
  14995. Light.prototype.copy.call( this, source );
  14996. this.distance = source.distance;
  14997. this.angle = source.angle;
  14998. this.penumbra = source.penumbra;
  14999. this.decay = source.decay;
  15000. this.target = source.target.clone();
  15001. this.shadow = source.shadow.clone();
  15002. return this;
  15003. }
  15004. } );
  15005. /**
  15006. * @author mrdoob / http://mrdoob.com/
  15007. */
  15008. function PointLight( color, intensity, distance, decay ) {
  15009. Light.call( this, color, intensity );
  15010. this.type = 'PointLight';
  15011. Object.defineProperty( this, 'power', {
  15012. get: function () {
  15013. // intensity = power per solid angle.
  15014. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15015. return this.intensity * 4 * Math.PI;
  15016. },
  15017. set: function ( power ) {
  15018. // intensity = power per solid angle.
  15019. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  15020. this.intensity = power / ( 4 * Math.PI );
  15021. }
  15022. } );
  15023. this.distance = ( distance !== undefined ) ? distance : 0;
  15024. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  15025. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  15026. }
  15027. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15028. constructor: PointLight,
  15029. isPointLight: true,
  15030. copy: function ( source ) {
  15031. Light.prototype.copy.call( this, source );
  15032. this.distance = source.distance;
  15033. this.decay = source.decay;
  15034. this.shadow = source.shadow.clone();
  15035. return this;
  15036. }
  15037. } );
  15038. /**
  15039. * @author mrdoob / http://mrdoob.com/
  15040. */
  15041. function DirectionalLightShadow( light ) {
  15042. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  15043. }
  15044. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  15045. constructor: DirectionalLightShadow
  15046. } );
  15047. /**
  15048. * @author mrdoob / http://mrdoob.com/
  15049. * @author alteredq / http://alteredqualia.com/
  15050. */
  15051. function DirectionalLight( color, intensity ) {
  15052. Light.call( this, color, intensity );
  15053. this.type = 'DirectionalLight';
  15054. this.position.copy( Object3D.DefaultUp );
  15055. this.updateMatrix();
  15056. this.target = new Object3D();
  15057. this.shadow = new DirectionalLightShadow();
  15058. }
  15059. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15060. constructor: DirectionalLight,
  15061. isDirectionalLight: true,
  15062. copy: function ( source ) {
  15063. Light.prototype.copy.call( this, source );
  15064. this.target = source.target.clone();
  15065. this.shadow = source.shadow.clone();
  15066. return this;
  15067. }
  15068. } );
  15069. /**
  15070. * @author mrdoob / http://mrdoob.com/
  15071. */
  15072. function AmbientLight( color, intensity ) {
  15073. Light.call( this, color, intensity );
  15074. this.type = 'AmbientLight';
  15075. this.castShadow = undefined;
  15076. }
  15077. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15078. constructor: AmbientLight,
  15079. isAmbientLight: true,
  15080. } );
  15081. /**
  15082. * @author tschw
  15083. * @author Ben Houston / http://clara.io/
  15084. * @author David Sarno / http://lighthaus.us/
  15085. */
  15086. exports.AnimationUtils = {
  15087. // same as Array.prototype.slice, but also works on typed arrays
  15088. arraySlice: function( array, from, to ) {
  15089. if ( exports.AnimationUtils.isTypedArray( array ) ) {
  15090. return new array.constructor( array.subarray( from, to ) );
  15091. }
  15092. return array.slice( from, to );
  15093. },
  15094. // converts an array to a specific type
  15095. convertArray: function( array, type, forceClone ) {
  15096. if ( ! array || // let 'undefined' and 'null' pass
  15097. ! forceClone && array.constructor === type ) return array;
  15098. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  15099. return new type( array ); // create typed array
  15100. }
  15101. return Array.prototype.slice.call( array ); // create Array
  15102. },
  15103. isTypedArray: function( object ) {
  15104. return ArrayBuffer.isView( object ) &&
  15105. ! ( object instanceof DataView );
  15106. },
  15107. // returns an array by which times and values can be sorted
  15108. getKeyframeOrder: function( times ) {
  15109. function compareTime( i, j ) {
  15110. return times[ i ] - times[ j ];
  15111. }
  15112. var n = times.length;
  15113. var result = new Array( n );
  15114. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  15115. result.sort( compareTime );
  15116. return result;
  15117. },
  15118. // uses the array previously returned by 'getKeyframeOrder' to sort data
  15119. sortedArray: function( values, stride, order ) {
  15120. var nValues = values.length;
  15121. var result = new values.constructor( nValues );
  15122. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  15123. var srcOffset = order[ i ] * stride;
  15124. for ( var j = 0; j !== stride; ++ j ) {
  15125. result[ dstOffset ++ ] = values[ srcOffset + j ];
  15126. }
  15127. }
  15128. return result;
  15129. },
  15130. // function for parsing AOS keyframe formats
  15131. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  15132. var i = 1, key = jsonKeys[ 0 ];
  15133. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  15134. key = jsonKeys[ i ++ ];
  15135. }
  15136. if ( key === undefined ) return; // no data
  15137. var value = key[ valuePropertyName ];
  15138. if ( value === undefined ) return; // no data
  15139. if ( Array.isArray( value ) ) {
  15140. do {
  15141. value = key[ valuePropertyName ];
  15142. if ( value !== undefined ) {
  15143. times.push( key.time );
  15144. values.push.apply( values, value ); // push all elements
  15145. }
  15146. key = jsonKeys[ i ++ ];
  15147. } while ( key !== undefined );
  15148. } else if ( value.toArray !== undefined ) {
  15149. // ...assume THREE.Math-ish
  15150. do {
  15151. value = key[ valuePropertyName ];
  15152. if ( value !== undefined ) {
  15153. times.push( key.time );
  15154. value.toArray( values, values.length );
  15155. }
  15156. key = jsonKeys[ i ++ ];
  15157. } while ( key !== undefined );
  15158. } else {
  15159. // otherwise push as-is
  15160. do {
  15161. value = key[ valuePropertyName ];
  15162. if ( value !== undefined ) {
  15163. times.push( key.time );
  15164. values.push( value );
  15165. }
  15166. key = jsonKeys[ i ++ ];
  15167. } while ( key !== undefined );
  15168. }
  15169. }
  15170. };
  15171. /**
  15172. * Abstract base class of interpolants over parametric samples.
  15173. *
  15174. * The parameter domain is one dimensional, typically the time or a path
  15175. * along a curve defined by the data.
  15176. *
  15177. * The sample values can have any dimensionality and derived classes may
  15178. * apply special interpretations to the data.
  15179. *
  15180. * This class provides the interval seek in a Template Method, deferring
  15181. * the actual interpolation to derived classes.
  15182. *
  15183. * Time complexity is O(1) for linear access crossing at most two points
  15184. * and O(log N) for random access, where N is the number of positions.
  15185. *
  15186. * References:
  15187. *
  15188. * http://www.oodesign.com/template-method-pattern.html
  15189. *
  15190. * @author tschw
  15191. */
  15192. function Interpolant(
  15193. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15194. this.parameterPositions = parameterPositions;
  15195. this._cachedIndex = 0;
  15196. this.resultBuffer = resultBuffer !== undefined ?
  15197. resultBuffer : new sampleValues.constructor( sampleSize );
  15198. this.sampleValues = sampleValues;
  15199. this.valueSize = sampleSize;
  15200. }
  15201. Interpolant.prototype = {
  15202. constructor: Interpolant,
  15203. evaluate: function( t ) {
  15204. var pp = this.parameterPositions,
  15205. i1 = this._cachedIndex,
  15206. t1 = pp[ i1 ],
  15207. t0 = pp[ i1 - 1 ];
  15208. validate_interval: {
  15209. seek: {
  15210. var right;
  15211. linear_scan: {
  15212. //- See http://jsperf.com/comparison-to-undefined/3
  15213. //- slower code:
  15214. //-
  15215. //- if ( t >= t1 || t1 === undefined ) {
  15216. forward_scan: if ( ! ( t < t1 ) ) {
  15217. for ( var giveUpAt = i1 + 2; ;) {
  15218. if ( t1 === undefined ) {
  15219. if ( t < t0 ) break forward_scan;
  15220. // after end
  15221. i1 = pp.length;
  15222. this._cachedIndex = i1;
  15223. return this.afterEnd_( i1 - 1, t, t0 );
  15224. }
  15225. if ( i1 === giveUpAt ) break; // this loop
  15226. t0 = t1;
  15227. t1 = pp[ ++ i1 ];
  15228. if ( t < t1 ) {
  15229. // we have arrived at the sought interval
  15230. break seek;
  15231. }
  15232. }
  15233. // prepare binary search on the right side of the index
  15234. right = pp.length;
  15235. break linear_scan;
  15236. }
  15237. //- slower code:
  15238. //- if ( t < t0 || t0 === undefined ) {
  15239. if ( ! ( t >= t0 ) ) {
  15240. // looping?
  15241. var t1global = pp[ 1 ];
  15242. if ( t < t1global ) {
  15243. i1 = 2; // + 1, using the scan for the details
  15244. t0 = t1global;
  15245. }
  15246. // linear reverse scan
  15247. for ( var giveUpAt = i1 - 2; ;) {
  15248. if ( t0 === undefined ) {
  15249. // before start
  15250. this._cachedIndex = 0;
  15251. return this.beforeStart_( 0, t, t1 );
  15252. }
  15253. if ( i1 === giveUpAt ) break; // this loop
  15254. t1 = t0;
  15255. t0 = pp[ -- i1 - 1 ];
  15256. if ( t >= t0 ) {
  15257. // we have arrived at the sought interval
  15258. break seek;
  15259. }
  15260. }
  15261. // prepare binary search on the left side of the index
  15262. right = i1;
  15263. i1 = 0;
  15264. break linear_scan;
  15265. }
  15266. // the interval is valid
  15267. break validate_interval;
  15268. } // linear scan
  15269. // binary search
  15270. while ( i1 < right ) {
  15271. var mid = ( i1 + right ) >>> 1;
  15272. if ( t < pp[ mid ] ) {
  15273. right = mid;
  15274. } else {
  15275. i1 = mid + 1;
  15276. }
  15277. }
  15278. t1 = pp[ i1 ];
  15279. t0 = pp[ i1 - 1 ];
  15280. // check boundary cases, again
  15281. if ( t0 === undefined ) {
  15282. this._cachedIndex = 0;
  15283. return this.beforeStart_( 0, t, t1 );
  15284. }
  15285. if ( t1 === undefined ) {
  15286. i1 = pp.length;
  15287. this._cachedIndex = i1;
  15288. return this.afterEnd_( i1 - 1, t0, t );
  15289. }
  15290. } // seek
  15291. this._cachedIndex = i1;
  15292. this.intervalChanged_( i1, t0, t1 );
  15293. } // validate_interval
  15294. return this.interpolate_( i1, t0, t, t1 );
  15295. },
  15296. settings: null, // optional, subclass-specific settings structure
  15297. // Note: The indirection allows central control of many interpolants.
  15298. // --- Protected interface
  15299. DefaultSettings_: {},
  15300. getSettings_: function() {
  15301. return this.settings || this.DefaultSettings_;
  15302. },
  15303. copySampleValue_: function( index ) {
  15304. // copies a sample value to the result buffer
  15305. var result = this.resultBuffer,
  15306. values = this.sampleValues,
  15307. stride = this.valueSize,
  15308. offset = index * stride;
  15309. for ( var i = 0; i !== stride; ++ i ) {
  15310. result[ i ] = values[ offset + i ];
  15311. }
  15312. return result;
  15313. },
  15314. // Template methods for derived classes:
  15315. interpolate_: function( i1, t0, t, t1 ) {
  15316. throw new Error( "call to abstract method" );
  15317. // implementations shall return this.resultBuffer
  15318. },
  15319. intervalChanged_: function( i1, t0, t1 ) {
  15320. // empty
  15321. }
  15322. };
  15323. Object.assign( Interpolant.prototype, {
  15324. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  15325. Interpolant.prototype.copySampleValue_,
  15326. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  15327. Interpolant.prototype.copySampleValue_
  15328. } );
  15329. /**
  15330. * Fast and simple cubic spline interpolant.
  15331. *
  15332. * It was derived from a Hermitian construction setting the first derivative
  15333. * at each sample position to the linear slope between neighboring positions
  15334. * over their parameter interval.
  15335. *
  15336. * @author tschw
  15337. */
  15338. function CubicInterpolant(
  15339. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15340. Interpolant.call(
  15341. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15342. this._weightPrev = -0;
  15343. this._offsetPrev = -0;
  15344. this._weightNext = -0;
  15345. this._offsetNext = -0;
  15346. }
  15347. CubicInterpolant.prototype =
  15348. Object.assign( Object.create( Interpolant.prototype ), {
  15349. constructor: CubicInterpolant,
  15350. DefaultSettings_: {
  15351. endingStart: ZeroCurvatureEnding,
  15352. endingEnd: ZeroCurvatureEnding
  15353. },
  15354. intervalChanged_: function( i1, t0, t1 ) {
  15355. var pp = this.parameterPositions,
  15356. iPrev = i1 - 2,
  15357. iNext = i1 + 1,
  15358. tPrev = pp[ iPrev ],
  15359. tNext = pp[ iNext ];
  15360. if ( tPrev === undefined ) {
  15361. switch ( this.getSettings_().endingStart ) {
  15362. case ZeroSlopeEnding:
  15363. // f'(t0) = 0
  15364. iPrev = i1;
  15365. tPrev = 2 * t0 - t1;
  15366. break;
  15367. case WrapAroundEnding:
  15368. // use the other end of the curve
  15369. iPrev = pp.length - 2;
  15370. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15371. break;
  15372. default: // ZeroCurvatureEnding
  15373. // f''(t0) = 0 a.k.a. Natural Spline
  15374. iPrev = i1;
  15375. tPrev = t1;
  15376. }
  15377. }
  15378. if ( tNext === undefined ) {
  15379. switch ( this.getSettings_().endingEnd ) {
  15380. case ZeroSlopeEnding:
  15381. // f'(tN) = 0
  15382. iNext = i1;
  15383. tNext = 2 * t1 - t0;
  15384. break;
  15385. case WrapAroundEnding:
  15386. // use the other end of the curve
  15387. iNext = 1;
  15388. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15389. break;
  15390. default: // ZeroCurvatureEnding
  15391. // f''(tN) = 0, a.k.a. Natural Spline
  15392. iNext = i1 - 1;
  15393. tNext = t0;
  15394. }
  15395. }
  15396. var halfDt = ( t1 - t0 ) * 0.5,
  15397. stride = this.valueSize;
  15398. this._weightPrev = halfDt / ( t0 - tPrev );
  15399. this._weightNext = halfDt / ( tNext - t1 );
  15400. this._offsetPrev = iPrev * stride;
  15401. this._offsetNext = iNext * stride;
  15402. },
  15403. interpolate_: function( i1, t0, t, t1 ) {
  15404. var result = this.resultBuffer,
  15405. values = this.sampleValues,
  15406. stride = this.valueSize,
  15407. o1 = i1 * stride, o0 = o1 - stride,
  15408. oP = this._offsetPrev, oN = this._offsetNext,
  15409. wP = this._weightPrev, wN = this._weightNext,
  15410. p = ( t - t0 ) / ( t1 - t0 ),
  15411. pp = p * p,
  15412. ppp = pp * p;
  15413. // evaluate polynomials
  15414. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  15415. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  15416. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15417. var sN = wN * ppp - wN * pp;
  15418. // combine data linearly
  15419. for ( var i = 0; i !== stride; ++ i ) {
  15420. result[ i ] =
  15421. sP * values[ oP + i ] +
  15422. s0 * values[ o0 + i ] +
  15423. s1 * values[ o1 + i ] +
  15424. sN * values[ oN + i ];
  15425. }
  15426. return result;
  15427. }
  15428. } );
  15429. /**
  15430. * @author tschw
  15431. */
  15432. function LinearInterpolant(
  15433. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15434. Interpolant.call(
  15435. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15436. }
  15437. LinearInterpolant.prototype =
  15438. Object.assign( Object.create( Interpolant.prototype ), {
  15439. constructor: LinearInterpolant,
  15440. interpolate_: function( i1, t0, t, t1 ) {
  15441. var result = this.resultBuffer,
  15442. values = this.sampleValues,
  15443. stride = this.valueSize,
  15444. offset1 = i1 * stride,
  15445. offset0 = offset1 - stride,
  15446. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15447. weight0 = 1 - weight1;
  15448. for ( var i = 0; i !== stride; ++ i ) {
  15449. result[ i ] =
  15450. values[ offset0 + i ] * weight0 +
  15451. values[ offset1 + i ] * weight1;
  15452. }
  15453. return result;
  15454. }
  15455. } );
  15456. /**
  15457. *
  15458. * Interpolant that evaluates to the sample value at the position preceeding
  15459. * the parameter.
  15460. *
  15461. * @author tschw
  15462. */
  15463. function DiscreteInterpolant(
  15464. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15465. Interpolant.call(
  15466. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15467. }
  15468. DiscreteInterpolant.prototype =
  15469. Object.assign( Object.create( Interpolant.prototype ), {
  15470. constructor: DiscreteInterpolant,
  15471. interpolate_: function( i1, t0, t, t1 ) {
  15472. return this.copySampleValue_( i1 - 1 );
  15473. }
  15474. } );
  15475. var KeyframeTrackPrototype;
  15476. KeyframeTrackPrototype = {
  15477. TimeBufferType: Float32Array,
  15478. ValueBufferType: Float32Array,
  15479. DefaultInterpolation: InterpolateLinear,
  15480. InterpolantFactoryMethodDiscrete: function( result ) {
  15481. return new DiscreteInterpolant(
  15482. this.times, this.values, this.getValueSize(), result );
  15483. },
  15484. InterpolantFactoryMethodLinear: function( result ) {
  15485. return new LinearInterpolant(
  15486. this.times, this.values, this.getValueSize(), result );
  15487. },
  15488. InterpolantFactoryMethodSmooth: function( result ) {
  15489. return new CubicInterpolant(
  15490. this.times, this.values, this.getValueSize(), result );
  15491. },
  15492. setInterpolation: function( interpolation ) {
  15493. var factoryMethod;
  15494. switch ( interpolation ) {
  15495. case InterpolateDiscrete:
  15496. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15497. break;
  15498. case InterpolateLinear:
  15499. factoryMethod = this.InterpolantFactoryMethodLinear;
  15500. break;
  15501. case InterpolateSmooth:
  15502. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15503. break;
  15504. }
  15505. if ( factoryMethod === undefined ) {
  15506. var message = "unsupported interpolation for " +
  15507. this.ValueTypeName + " keyframe track named " + this.name;
  15508. if ( this.createInterpolant === undefined ) {
  15509. // fall back to default, unless the default itself is messed up
  15510. if ( interpolation !== this.DefaultInterpolation ) {
  15511. this.setInterpolation( this.DefaultInterpolation );
  15512. } else {
  15513. throw new Error( message ); // fatal, in this case
  15514. }
  15515. }
  15516. console.warn( message );
  15517. return;
  15518. }
  15519. this.createInterpolant = factoryMethod;
  15520. },
  15521. getInterpolation: function() {
  15522. switch ( this.createInterpolant ) {
  15523. case this.InterpolantFactoryMethodDiscrete:
  15524. return InterpolateDiscrete;
  15525. case this.InterpolantFactoryMethodLinear:
  15526. return InterpolateLinear;
  15527. case this.InterpolantFactoryMethodSmooth:
  15528. return InterpolateSmooth;
  15529. }
  15530. },
  15531. getValueSize: function() {
  15532. return this.values.length / this.times.length;
  15533. },
  15534. // move all keyframes either forwards or backwards in time
  15535. shift: function( timeOffset ) {
  15536. if( timeOffset !== 0.0 ) {
  15537. var times = this.times;
  15538. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15539. times[ i ] += timeOffset;
  15540. }
  15541. }
  15542. return this;
  15543. },
  15544. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15545. scale: function( timeScale ) {
  15546. if( timeScale !== 1.0 ) {
  15547. var times = this.times;
  15548. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15549. times[ i ] *= timeScale;
  15550. }
  15551. }
  15552. return this;
  15553. },
  15554. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15555. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15556. trim: function( startTime, endTime ) {
  15557. var times = this.times,
  15558. nKeys = times.length,
  15559. from = 0,
  15560. to = nKeys - 1;
  15561. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  15562. while ( to !== -1 && times[ to ] > endTime ) -- to;
  15563. ++ to; // inclusive -> exclusive bound
  15564. if( from !== 0 || to !== nKeys ) {
  15565. // empty tracks are forbidden, so keep at least one keyframe
  15566. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  15567. var stride = this.getValueSize();
  15568. this.times = exports.AnimationUtils.arraySlice( times, from, to );
  15569. this.values = exports.AnimationUtils.
  15570. arraySlice( this.values, from * stride, to * stride );
  15571. }
  15572. return this;
  15573. },
  15574. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15575. validate: function() {
  15576. var valid = true;
  15577. var valueSize = this.getValueSize();
  15578. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15579. console.error( "invalid value size in track", this );
  15580. valid = false;
  15581. }
  15582. var times = this.times,
  15583. values = this.values,
  15584. nKeys = times.length;
  15585. if( nKeys === 0 ) {
  15586. console.error( "track is empty", this );
  15587. valid = false;
  15588. }
  15589. var prevTime = null;
  15590. for( var i = 0; i !== nKeys; i ++ ) {
  15591. var currTime = times[ i ];
  15592. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15593. console.error( "time is not a valid number", this, i, currTime );
  15594. valid = false;
  15595. break;
  15596. }
  15597. if( prevTime !== null && prevTime > currTime ) {
  15598. console.error( "out of order keys", this, i, currTime, prevTime );
  15599. valid = false;
  15600. break;
  15601. }
  15602. prevTime = currTime;
  15603. }
  15604. if ( values !== undefined ) {
  15605. if ( exports.AnimationUtils.isTypedArray( values ) ) {
  15606. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  15607. var value = values[ i ];
  15608. if ( isNaN( value ) ) {
  15609. console.error( "value is not a valid number", this, i, value );
  15610. valid = false;
  15611. break;
  15612. }
  15613. }
  15614. }
  15615. }
  15616. return valid;
  15617. },
  15618. // removes equivalent sequential keys as common in morph target sequences
  15619. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15620. optimize: function() {
  15621. var times = this.times,
  15622. values = this.values,
  15623. stride = this.getValueSize(),
  15624. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15625. writeIndex = 1,
  15626. lastIndex = times.length - 1;
  15627. for( var i = 1; i < lastIndex; ++ i ) {
  15628. var keep = false;
  15629. var time = times[ i ];
  15630. var timeNext = times[ i + 1 ];
  15631. // remove adjacent keyframes scheduled at the same time
  15632. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  15633. if ( ! smoothInterpolation ) {
  15634. // remove unnecessary keyframes same as their neighbors
  15635. var offset = i * stride,
  15636. offsetP = offset - stride,
  15637. offsetN = offset + stride;
  15638. for ( var j = 0; j !== stride; ++ j ) {
  15639. var value = values[ offset + j ];
  15640. if ( value !== values[ offsetP + j ] ||
  15641. value !== values[ offsetN + j ] ) {
  15642. keep = true;
  15643. break;
  15644. }
  15645. }
  15646. } else keep = true;
  15647. }
  15648. // in-place compaction
  15649. if ( keep ) {
  15650. if ( i !== writeIndex ) {
  15651. times[ writeIndex ] = times[ i ];
  15652. var readOffset = i * stride,
  15653. writeOffset = writeIndex * stride;
  15654. for ( var j = 0; j !== stride; ++ j )
  15655. values[ writeOffset + j ] = values[ readOffset + j ];
  15656. }
  15657. ++ writeIndex;
  15658. }
  15659. }
  15660. // flush last keyframe (compaction looks ahead)
  15661. times[ writeIndex ++ ] = times[ lastIndex ];
  15662. for ( var readOffset = lastIndex * stride, j = 0; j !== stride; ++ j )
  15663. values[ writeOffset + j ] = values[ readOffset + j ];
  15664. if ( writeIndex !== times.length ) {
  15665. this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex );
  15666. this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  15667. }
  15668. return this;
  15669. }
  15670. }
  15671. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  15672. if( name === undefined ) throw new Error( "track name is undefined" );
  15673. if( times === undefined || times.length === 0 ) {
  15674. throw new Error( "no keyframes in track named " + name );
  15675. }
  15676. this.name = name;
  15677. this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType );
  15678. this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType );
  15679. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15680. this.validate();
  15681. this.optimize();
  15682. }
  15683. /**
  15684. *
  15685. * A Track of vectored keyframe values.
  15686. *
  15687. *
  15688. * @author Ben Houston / http://clara.io/
  15689. * @author David Sarno / http://lighthaus.us/
  15690. * @author tschw
  15691. */
  15692. function VectorKeyframeTrack( name, times, values, interpolation ) {
  15693. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15694. }
  15695. VectorKeyframeTrack.prototype =
  15696. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15697. constructor: VectorKeyframeTrack,
  15698. ValueTypeName: 'vector'
  15699. // ValueBufferType is inherited
  15700. // DefaultInterpolation is inherited
  15701. } );
  15702. /**
  15703. * Spherical linear unit quaternion interpolant.
  15704. *
  15705. * @author tschw
  15706. */
  15707. function QuaternionLinearInterpolant(
  15708. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15709. Interpolant.call(
  15710. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15711. }
  15712. QuaternionLinearInterpolant.prototype =
  15713. Object.assign( Object.create( Interpolant.prototype ), {
  15714. constructor: QuaternionLinearInterpolant,
  15715. interpolate_: function( i1, t0, t, t1 ) {
  15716. var result = this.resultBuffer,
  15717. values = this.sampleValues,
  15718. stride = this.valueSize,
  15719. offset = i1 * stride,
  15720. alpha = ( t - t0 ) / ( t1 - t0 );
  15721. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  15722. Quaternion.slerpFlat( result, 0,
  15723. values, offset - stride, values, offset, alpha );
  15724. }
  15725. return result;
  15726. }
  15727. } );
  15728. /**
  15729. *
  15730. * A Track of quaternion keyframe values.
  15731. *
  15732. * @author Ben Houston / http://clara.io/
  15733. * @author David Sarno / http://lighthaus.us/
  15734. * @author tschw
  15735. */
  15736. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  15737. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15738. }
  15739. QuaternionKeyframeTrack.prototype =
  15740. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15741. constructor: QuaternionKeyframeTrack,
  15742. ValueTypeName: 'quaternion',
  15743. // ValueBufferType is inherited
  15744. DefaultInterpolation: InterpolateLinear,
  15745. InterpolantFactoryMethodLinear: function( result ) {
  15746. return new QuaternionLinearInterpolant(
  15747. this.times, this.values, this.getValueSize(), result );
  15748. },
  15749. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  15750. } );
  15751. /**
  15752. *
  15753. * A Track of numeric keyframe values.
  15754. *
  15755. * @author Ben Houston / http://clara.io/
  15756. * @author David Sarno / http://lighthaus.us/
  15757. * @author tschw
  15758. */
  15759. function NumberKeyframeTrack( name, times, values, interpolation ) {
  15760. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15761. }
  15762. NumberKeyframeTrack.prototype =
  15763. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15764. constructor: NumberKeyframeTrack,
  15765. ValueTypeName: 'number',
  15766. // ValueBufferType is inherited
  15767. // DefaultInterpolation is inherited
  15768. } );
  15769. /**
  15770. *
  15771. * A Track that interpolates Strings
  15772. *
  15773. *
  15774. * @author Ben Houston / http://clara.io/
  15775. * @author David Sarno / http://lighthaus.us/
  15776. * @author tschw
  15777. */
  15778. function StringKeyframeTrack( name, times, values, interpolation ) {
  15779. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15780. }
  15781. StringKeyframeTrack.prototype =
  15782. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15783. constructor: StringKeyframeTrack,
  15784. ValueTypeName: 'string',
  15785. ValueBufferType: Array,
  15786. DefaultInterpolation: InterpolateDiscrete,
  15787. InterpolantFactoryMethodLinear: undefined,
  15788. InterpolantFactoryMethodSmooth: undefined
  15789. } );
  15790. /**
  15791. *
  15792. * A Track of Boolean keyframe values.
  15793. *
  15794. *
  15795. * @author Ben Houston / http://clara.io/
  15796. * @author David Sarno / http://lighthaus.us/
  15797. * @author tschw
  15798. */
  15799. function BooleanKeyframeTrack( name, times, values ) {
  15800. KeyframeTrackConstructor.call( this, name, times, values );
  15801. }
  15802. BooleanKeyframeTrack.prototype =
  15803. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15804. constructor: BooleanKeyframeTrack,
  15805. ValueTypeName: 'bool',
  15806. ValueBufferType: Array,
  15807. DefaultInterpolation: InterpolateDiscrete,
  15808. InterpolantFactoryMethodLinear: undefined,
  15809. InterpolantFactoryMethodSmooth: undefined
  15810. // Note: Actually this track could have a optimized / compressed
  15811. // representation of a single value and a custom interpolant that
  15812. // computes "firstValue ^ isOdd( index )".
  15813. } );
  15814. /**
  15815. *
  15816. * A Track of keyframe values that represent color.
  15817. *
  15818. *
  15819. * @author Ben Houston / http://clara.io/
  15820. * @author David Sarno / http://lighthaus.us/
  15821. * @author tschw
  15822. */
  15823. function ColorKeyframeTrack( name, times, values, interpolation ) {
  15824. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15825. }
  15826. ColorKeyframeTrack.prototype =
  15827. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15828. constructor: ColorKeyframeTrack,
  15829. ValueTypeName: 'color'
  15830. // ValueBufferType is inherited
  15831. // DefaultInterpolation is inherited
  15832. // Note: Very basic implementation and nothing special yet.
  15833. // However, this is the place for color space parameterization.
  15834. } );
  15835. /**
  15836. *
  15837. * A timed sequence of keyframes for a specific property.
  15838. *
  15839. *
  15840. * @author Ben Houston / http://clara.io/
  15841. * @author David Sarno / http://lighthaus.us/
  15842. * @author tschw
  15843. */
  15844. function KeyframeTrack( name, times, values, interpolation ) {
  15845. KeyframeTrackConstructor.apply( this, arguments );
  15846. }
  15847. KeyframeTrack.prototype = KeyframeTrackPrototype;
  15848. KeyframeTrackPrototype.constructor = KeyframeTrack;
  15849. // Static methods:
  15850. Object.assign( KeyframeTrack, {
  15851. // Serialization (in static context, because of constructor invocation
  15852. // and automatic invocation of .toJSON):
  15853. parse: function( json ) {
  15854. if( json.type === undefined ) {
  15855. throw new Error( "track type undefined, can not parse" );
  15856. }
  15857. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  15858. if ( json.times === undefined ) {
  15859. var times = [], values = [];
  15860. exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  15861. json.times = times;
  15862. json.values = values;
  15863. }
  15864. // derived classes can define a static parse method
  15865. if ( trackType.parse !== undefined ) {
  15866. return trackType.parse( json );
  15867. } else {
  15868. // by default, we asssume a constructor compatible with the base
  15869. return new trackType(
  15870. json.name, json.times, json.values, json.interpolation );
  15871. }
  15872. },
  15873. toJSON: function( track ) {
  15874. var trackType = track.constructor;
  15875. var json;
  15876. // derived classes can define a static toJSON method
  15877. if ( trackType.toJSON !== undefined ) {
  15878. json = trackType.toJSON( track );
  15879. } else {
  15880. // by default, we assume the data can be serialized as-is
  15881. json = {
  15882. 'name': track.name,
  15883. 'times': exports.AnimationUtils.convertArray( track.times, Array ),
  15884. 'values': exports.AnimationUtils.convertArray( track.values, Array )
  15885. };
  15886. var interpolation = track.getInterpolation();
  15887. if ( interpolation !== track.DefaultInterpolation ) {
  15888. json.interpolation = interpolation;
  15889. }
  15890. }
  15891. json.type = track.ValueTypeName; // mandatory
  15892. return json;
  15893. },
  15894. _getTrackTypeForValueTypeName: function( typeName ) {
  15895. switch( typeName.toLowerCase() ) {
  15896. case "scalar":
  15897. case "double":
  15898. case "float":
  15899. case "number":
  15900. case "integer":
  15901. return NumberKeyframeTrack;
  15902. case "vector":
  15903. case "vector2":
  15904. case "vector3":
  15905. case "vector4":
  15906. return VectorKeyframeTrack;
  15907. case "color":
  15908. return ColorKeyframeTrack;
  15909. case "quaternion":
  15910. return QuaternionKeyframeTrack;
  15911. case "bool":
  15912. case "boolean":
  15913. return BooleanKeyframeTrack;
  15914. case "string":
  15915. return StringKeyframeTrack;
  15916. }
  15917. throw new Error( "Unsupported typeName: " + typeName );
  15918. }
  15919. } );
  15920. /**
  15921. *
  15922. * Reusable set of Tracks that represent an animation.
  15923. *
  15924. * @author Ben Houston / http://clara.io/
  15925. * @author David Sarno / http://lighthaus.us/
  15926. */
  15927. function AnimationClip( name, duration, tracks ) {
  15928. this.name = name;
  15929. this.tracks = tracks;
  15930. this.duration = ( duration !== undefined ) ? duration : -1;
  15931. this.uuid = exports.Math.generateUUID();
  15932. // this means it should figure out its duration by scanning the tracks
  15933. if ( this.duration < 0 ) {
  15934. this.resetDuration();
  15935. }
  15936. // maybe only do these on demand, as doing them here could potentially slow down loading
  15937. // but leaving these here during development as this ensures a lot of testing of these functions
  15938. this.trim();
  15939. this.optimize();
  15940. }
  15941. AnimationClip.prototype = {
  15942. constructor: AnimationClip,
  15943. resetDuration: function() {
  15944. var tracks = this.tracks,
  15945. duration = 0;
  15946. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  15947. var track = this.tracks[ i ];
  15948. duration = Math.max(
  15949. duration, track.times[ track.times.length - 1 ] );
  15950. }
  15951. this.duration = duration;
  15952. },
  15953. trim: function() {
  15954. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15955. this.tracks[ i ].trim( 0, this.duration );
  15956. }
  15957. return this;
  15958. },
  15959. optimize: function() {
  15960. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15961. this.tracks[ i ].optimize();
  15962. }
  15963. return this;
  15964. }
  15965. };
  15966. // Static methods:
  15967. Object.assign( AnimationClip, {
  15968. parse: function( json ) {
  15969. var tracks = [],
  15970. jsonTracks = json.tracks,
  15971. frameTime = 1.0 / ( json.fps || 1.0 );
  15972. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15973. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  15974. }
  15975. return new AnimationClip( json.name, json.duration, tracks );
  15976. },
  15977. toJSON: function( clip ) {
  15978. var tracks = [],
  15979. clipTracks = clip.tracks;
  15980. var json = {
  15981. 'name': clip.name,
  15982. 'duration': clip.duration,
  15983. 'tracks': tracks
  15984. };
  15985. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15986. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15987. }
  15988. return json;
  15989. },
  15990. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  15991. var numMorphTargets = morphTargetSequence.length;
  15992. var tracks = [];
  15993. for ( var i = 0; i < numMorphTargets; i ++ ) {
  15994. var times = [];
  15995. var values = [];
  15996. times.push(
  15997. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15998. i,
  15999. ( i + 1 ) % numMorphTargets );
  16000. values.push( 0, 1, 0 );
  16001. var order = exports.AnimationUtils.getKeyframeOrder( times );
  16002. times = exports.AnimationUtils.sortedArray( times, 1, order );
  16003. values = exports.AnimationUtils.sortedArray( values, 1, order );
  16004. // if there is a key at the first frame, duplicate it as the
  16005. // last frame as well for perfect loop.
  16006. if ( ! noLoop && times[ 0 ] === 0 ) {
  16007. times.push( numMorphTargets );
  16008. values.push( values[ 0 ] );
  16009. }
  16010. tracks.push(
  16011. new NumberKeyframeTrack(
  16012. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  16013. times, values
  16014. ).scale( 1.0 / fps ) );
  16015. }
  16016. return new AnimationClip( name, -1, tracks );
  16017. },
  16018. findByName: function( objectOrClipArray, name ) {
  16019. var clipArray = objectOrClipArray;
  16020. if ( ! Array.isArray( objectOrClipArray ) ) {
  16021. var o = objectOrClipArray;
  16022. clipArray = o.geometry && o.geometry.animations || o.animations;
  16023. }
  16024. for ( var i = 0; i < clipArray.length; i ++ ) {
  16025. if ( clipArray[ i ].name === name ) {
  16026. return clipArray[ i ];
  16027. }
  16028. }
  16029. return null;
  16030. },
  16031. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  16032. var animationToMorphTargets = {};
  16033. // tested with https://regex101.com/ on trick sequences
  16034. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  16035. var pattern = /^([\w-]*?)([\d]+)$/;
  16036. // sort morph target names into animation groups based
  16037. // patterns like Walk_001, Walk_002, Run_001, Run_002
  16038. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  16039. var morphTarget = morphTargets[ i ];
  16040. var parts = morphTarget.name.match( pattern );
  16041. if ( parts && parts.length > 1 ) {
  16042. var name = parts[ 1 ];
  16043. var animationMorphTargets = animationToMorphTargets[ name ];
  16044. if ( ! animationMorphTargets ) {
  16045. animationToMorphTargets[ name ] = animationMorphTargets = [];
  16046. }
  16047. animationMorphTargets.push( morphTarget );
  16048. }
  16049. }
  16050. var clips = [];
  16051. for ( var name in animationToMorphTargets ) {
  16052. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  16053. }
  16054. return clips;
  16055. },
  16056. // parse the animation.hierarchy format
  16057. parseAnimation: function( animation, bones, nodeName ) {
  16058. if ( ! animation ) {
  16059. console.error( " no animation in JSONLoader data" );
  16060. return null;
  16061. }
  16062. var addNonemptyTrack = function(
  16063. trackType, trackName, animationKeys, propertyName, destTracks ) {
  16064. // only return track if there are actually keys.
  16065. if ( animationKeys.length !== 0 ) {
  16066. var times = [];
  16067. var values = [];
  16068. exports.AnimationUtils.flattenJSON(
  16069. animationKeys, times, values, propertyName );
  16070. // empty keys are filtered out, so check again
  16071. if ( times.length !== 0 ) {
  16072. destTracks.push( new trackType( trackName, times, values ) );
  16073. }
  16074. }
  16075. };
  16076. var tracks = [];
  16077. var clipName = animation.name || 'default';
  16078. // automatic length determination in AnimationClip.
  16079. var duration = animation.length || -1;
  16080. var fps = animation.fps || 30;
  16081. var hierarchyTracks = animation.hierarchy || [];
  16082. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  16083. var animationKeys = hierarchyTracks[ h ].keys;
  16084. // skip empty tracks
  16085. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  16086. // process morph targets in a way exactly compatible
  16087. // with AnimationHandler.init( animation )
  16088. if ( animationKeys[0].morphTargets ) {
  16089. // figure out all morph targets used in this track
  16090. var morphTargetNames = {};
  16091. for ( var k = 0; k < animationKeys.length; k ++ ) {
  16092. if ( animationKeys[k].morphTargets ) {
  16093. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  16094. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  16095. }
  16096. }
  16097. }
  16098. // create a track for each morph target with all zero
  16099. // morphTargetInfluences except for the keys in which
  16100. // the morphTarget is named.
  16101. for ( var morphTargetName in morphTargetNames ) {
  16102. var times = [];
  16103. var values = [];
  16104. for ( var m = 0;
  16105. m !== animationKeys[k].morphTargets.length; ++ m ) {
  16106. var animationKey = animationKeys[k];
  16107. times.push( animationKey.time );
  16108. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  16109. }
  16110. tracks.push( new NumberKeyframeTrack(
  16111. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  16112. }
  16113. duration = morphTargetNames.length * ( fps || 1.0 );
  16114. } else {
  16115. // ...assume skeletal animation
  16116. var boneName = '.bones[' + bones[ h ].name + ']';
  16117. addNonemptyTrack(
  16118. VectorKeyframeTrack, boneName + '.position',
  16119. animationKeys, 'pos', tracks );
  16120. addNonemptyTrack(
  16121. QuaternionKeyframeTrack, boneName + '.quaternion',
  16122. animationKeys, 'rot', tracks );
  16123. addNonemptyTrack(
  16124. VectorKeyframeTrack, boneName + '.scale',
  16125. animationKeys, 'scl', tracks );
  16126. }
  16127. }
  16128. if ( tracks.length === 0 ) {
  16129. return null;
  16130. }
  16131. var clip = new AnimationClip( clipName, duration, tracks );
  16132. return clip;
  16133. }
  16134. } );
  16135. /**
  16136. * @author mrdoob / http://mrdoob.com/
  16137. */
  16138. function MaterialLoader( manager ) {
  16139. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16140. this.textures = {};
  16141. }
  16142. Object.assign( MaterialLoader.prototype, {
  16143. load: function ( url, onLoad, onProgress, onError ) {
  16144. var scope = this;
  16145. var loader = new XHRLoader( scope.manager );
  16146. loader.load( url, function ( text ) {
  16147. onLoad( scope.parse( JSON.parse( text ) ) );
  16148. }, onProgress, onError );
  16149. },
  16150. setTextures: function ( value ) {
  16151. this.textures = value;
  16152. },
  16153. parse: function ( json ) {
  16154. var textures = this.textures;
  16155. function getTexture( name ) {
  16156. if ( textures[ name ] === undefined ) {
  16157. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16158. }
  16159. return textures[ name ];
  16160. }
  16161. var material = new THREE[ json.type ]();
  16162. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16163. if ( json.name !== undefined ) material.name = json.name;
  16164. if ( json.color !== undefined ) material.color.setHex( json.color );
  16165. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16166. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16167. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16168. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  16169. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16170. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  16171. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16172. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16173. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  16174. if ( json.fog !== undefined ) material.fog = json.fog;
  16175. if ( json.shading !== undefined ) material.shading = json.shading;
  16176. if ( json.blending !== undefined ) material.blending = json.blending;
  16177. if ( json.side !== undefined ) material.side = json.side;
  16178. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16179. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16180. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16181. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16182. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16183. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16184. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16185. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16186. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16187. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16188. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  16189. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  16190. // for PointsMaterial
  16191. if ( json.size !== undefined ) material.size = json.size;
  16192. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16193. // maps
  16194. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16195. if ( json.alphaMap !== undefined ) {
  16196. material.alphaMap = getTexture( json.alphaMap );
  16197. material.transparent = true;
  16198. }
  16199. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16200. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16201. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16202. if ( json.normalScale !== undefined ) {
  16203. var normalScale = json.normalScale;
  16204. if ( Array.isArray( normalScale ) === false ) {
  16205. // Blender exporter used to export a scalar. See #7459
  16206. normalScale = [ normalScale, normalScale ];
  16207. }
  16208. material.normalScale = new Vector2().fromArray( normalScale );
  16209. }
  16210. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16211. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16212. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16213. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16214. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16215. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16216. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16217. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16218. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16219. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16220. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16221. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16222. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16223. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16224. // MultiMaterial
  16225. if ( json.materials !== undefined ) {
  16226. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  16227. material.materials.push( this.parse( json.materials[ i ] ) );
  16228. }
  16229. }
  16230. return material;
  16231. }
  16232. } );
  16233. /**
  16234. * @author mrdoob / http://mrdoob.com/
  16235. */
  16236. function BufferGeometryLoader( manager ) {
  16237. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16238. }
  16239. Object.assign( BufferGeometryLoader.prototype, {
  16240. load: function ( url, onLoad, onProgress, onError ) {
  16241. var scope = this;
  16242. var loader = new XHRLoader( scope.manager );
  16243. loader.load( url, function ( text ) {
  16244. onLoad( scope.parse( JSON.parse( text ) ) );
  16245. }, onProgress, onError );
  16246. },
  16247. parse: function ( json ) {
  16248. var geometry = new BufferGeometry();
  16249. var index = json.data.index;
  16250. var TYPED_ARRAYS = {
  16251. 'Int8Array': Int8Array,
  16252. 'Uint8Array': Uint8Array,
  16253. 'Uint8ClampedArray': Uint8ClampedArray,
  16254. 'Int16Array': Int16Array,
  16255. 'Uint16Array': Uint16Array,
  16256. 'Int32Array': Int32Array,
  16257. 'Uint32Array': Uint32Array,
  16258. 'Float32Array': Float32Array,
  16259. 'Float64Array': Float64Array
  16260. };
  16261. if ( index !== undefined ) {
  16262. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  16263. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16264. }
  16265. var attributes = json.data.attributes;
  16266. for ( var key in attributes ) {
  16267. var attribute = attributes[ key ];
  16268. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  16269. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  16270. }
  16271. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16272. if ( groups !== undefined ) {
  16273. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  16274. var group = groups[ i ];
  16275. geometry.addGroup( group.start, group.count, group.materialIndex );
  16276. }
  16277. }
  16278. var boundingSphere = json.data.boundingSphere;
  16279. if ( boundingSphere !== undefined ) {
  16280. var center = new Vector3();
  16281. if ( boundingSphere.center !== undefined ) {
  16282. center.fromArray( boundingSphere.center );
  16283. }
  16284. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  16285. }
  16286. return geometry;
  16287. }
  16288. } );
  16289. /**
  16290. * @author alteredq / http://alteredqualia.com/
  16291. */
  16292. function Loader() {
  16293. this.onLoadStart = function () {};
  16294. this.onLoadProgress = function () {};
  16295. this.onLoadComplete = function () {};
  16296. }
  16297. Loader.prototype = {
  16298. constructor: Loader,
  16299. crossOrigin: undefined,
  16300. extractUrlBase: function ( url ) {
  16301. var parts = url.split( '/' );
  16302. if ( parts.length === 1 ) return './';
  16303. parts.pop();
  16304. return parts.join( '/' ) + '/';
  16305. },
  16306. initMaterials: function ( materials, texturePath, crossOrigin ) {
  16307. var array = [];
  16308. for ( var i = 0; i < materials.length; ++ i ) {
  16309. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  16310. }
  16311. return array;
  16312. },
  16313. createMaterial: ( function () {
  16314. var color, textureLoader, materialLoader;
  16315. return function createMaterial( m, texturePath, crossOrigin ) {
  16316. if ( color === undefined ) color = new Color();
  16317. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  16318. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  16319. // convert from old material format
  16320. var textures = {};
  16321. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  16322. var fullPath = texturePath + path;
  16323. var loader = Loader.Handlers.get( fullPath );
  16324. var texture;
  16325. if ( loader !== null ) {
  16326. texture = loader.load( fullPath );
  16327. } else {
  16328. textureLoader.setCrossOrigin( crossOrigin );
  16329. texture = textureLoader.load( fullPath );
  16330. }
  16331. if ( repeat !== undefined ) {
  16332. texture.repeat.fromArray( repeat );
  16333. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  16334. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  16335. }
  16336. if ( offset !== undefined ) {
  16337. texture.offset.fromArray( offset );
  16338. }
  16339. if ( wrap !== undefined ) {
  16340. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  16341. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  16342. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  16343. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  16344. }
  16345. if ( anisotropy !== undefined ) {
  16346. texture.anisotropy = anisotropy;
  16347. }
  16348. var uuid = exports.Math.generateUUID();
  16349. textures[ uuid ] = texture;
  16350. return uuid;
  16351. }
  16352. //
  16353. var json = {
  16354. uuid: exports.Math.generateUUID(),
  16355. type: 'MeshLambertMaterial'
  16356. };
  16357. for ( var name in m ) {
  16358. var value = m[ name ];
  16359. switch ( name ) {
  16360. case 'DbgColor':
  16361. case 'DbgIndex':
  16362. case 'opticalDensity':
  16363. case 'illumination':
  16364. break;
  16365. case 'DbgName':
  16366. json.name = value;
  16367. break;
  16368. case 'blending':
  16369. json.blending = THREE[ value ];
  16370. break;
  16371. case 'colorAmbient':
  16372. case 'mapAmbient':
  16373. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  16374. break;
  16375. case 'colorDiffuse':
  16376. json.color = color.fromArray( value ).getHex();
  16377. break;
  16378. case 'colorSpecular':
  16379. json.specular = color.fromArray( value ).getHex();
  16380. break;
  16381. case 'colorEmissive':
  16382. json.emissive = color.fromArray( value ).getHex();
  16383. break;
  16384. case 'specularCoef':
  16385. json.shininess = value;
  16386. break;
  16387. case 'shading':
  16388. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  16389. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  16390. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  16391. break;
  16392. case 'mapDiffuse':
  16393. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  16394. break;
  16395. case 'mapDiffuseRepeat':
  16396. case 'mapDiffuseOffset':
  16397. case 'mapDiffuseWrap':
  16398. case 'mapDiffuseAnisotropy':
  16399. break;
  16400. case 'mapEmissive':
  16401. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  16402. break;
  16403. case 'mapEmissiveRepeat':
  16404. case 'mapEmissiveOffset':
  16405. case 'mapEmissiveWrap':
  16406. case 'mapEmissiveAnisotropy':
  16407. break;
  16408. case 'mapLight':
  16409. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  16410. break;
  16411. case 'mapLightRepeat':
  16412. case 'mapLightOffset':
  16413. case 'mapLightWrap':
  16414. case 'mapLightAnisotropy':
  16415. break;
  16416. case 'mapAO':
  16417. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  16418. break;
  16419. case 'mapAORepeat':
  16420. case 'mapAOOffset':
  16421. case 'mapAOWrap':
  16422. case 'mapAOAnisotropy':
  16423. break;
  16424. case 'mapBump':
  16425. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  16426. break;
  16427. case 'mapBumpScale':
  16428. json.bumpScale = value;
  16429. break;
  16430. case 'mapBumpRepeat':
  16431. case 'mapBumpOffset':
  16432. case 'mapBumpWrap':
  16433. case 'mapBumpAnisotropy':
  16434. break;
  16435. case 'mapNormal':
  16436. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  16437. break;
  16438. case 'mapNormalFactor':
  16439. json.normalScale = [ value, value ];
  16440. break;
  16441. case 'mapNormalRepeat':
  16442. case 'mapNormalOffset':
  16443. case 'mapNormalWrap':
  16444. case 'mapNormalAnisotropy':
  16445. break;
  16446. case 'mapSpecular':
  16447. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  16448. break;
  16449. case 'mapSpecularRepeat':
  16450. case 'mapSpecularOffset':
  16451. case 'mapSpecularWrap':
  16452. case 'mapSpecularAnisotropy':
  16453. break;
  16454. case 'mapMetalness':
  16455. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  16456. break;
  16457. case 'mapMetalnessRepeat':
  16458. case 'mapMetalnessOffset':
  16459. case 'mapMetalnessWrap':
  16460. case 'mapMetalnessAnisotropy':
  16461. break;
  16462. case 'mapRoughness':
  16463. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  16464. break;
  16465. case 'mapRoughnessRepeat':
  16466. case 'mapRoughnessOffset':
  16467. case 'mapRoughnessWrap':
  16468. case 'mapRoughnessAnisotropy':
  16469. break;
  16470. case 'mapAlpha':
  16471. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  16472. break;
  16473. case 'mapAlphaRepeat':
  16474. case 'mapAlphaOffset':
  16475. case 'mapAlphaWrap':
  16476. case 'mapAlphaAnisotropy':
  16477. break;
  16478. case 'flipSided':
  16479. json.side = BackSide;
  16480. break;
  16481. case 'doubleSided':
  16482. json.side = DoubleSide;
  16483. break;
  16484. case 'transparency':
  16485. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  16486. json.opacity = value;
  16487. break;
  16488. case 'depthTest':
  16489. case 'depthWrite':
  16490. case 'colorWrite':
  16491. case 'opacity':
  16492. case 'reflectivity':
  16493. case 'transparent':
  16494. case 'visible':
  16495. case 'wireframe':
  16496. json[ name ] = value;
  16497. break;
  16498. case 'vertexColors':
  16499. if ( value === true ) json.vertexColors = VertexColors;
  16500. if ( value === 'face' ) json.vertexColors = FaceColors;
  16501. break;
  16502. default:
  16503. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  16504. break;
  16505. }
  16506. }
  16507. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  16508. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  16509. if ( json.opacity < 1 ) json.transparent = true;
  16510. materialLoader.setTextures( textures );
  16511. return materialLoader.parse( json );
  16512. };
  16513. } )()
  16514. };
  16515. Loader.Handlers = {
  16516. handlers: [],
  16517. add: function ( regex, loader ) {
  16518. this.handlers.push( regex, loader );
  16519. },
  16520. get: function ( file ) {
  16521. var handlers = this.handlers;
  16522. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  16523. var regex = handlers[ i ];
  16524. var loader = handlers[ i + 1 ];
  16525. if ( regex.test( file ) ) {
  16526. return loader;
  16527. }
  16528. }
  16529. return null;
  16530. }
  16531. };
  16532. /**
  16533. * @author mrdoob / http://mrdoob.com/
  16534. * @author alteredq / http://alteredqualia.com/
  16535. */
  16536. function JSONLoader( manager ) {
  16537. if ( typeof manager === 'boolean' ) {
  16538. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  16539. manager = undefined;
  16540. }
  16541. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16542. this.withCredentials = false;
  16543. }
  16544. Object.assign( JSONLoader.prototype, {
  16545. load: function( url, onLoad, onProgress, onError ) {
  16546. var scope = this;
  16547. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  16548. var loader = new XHRLoader( this.manager );
  16549. loader.setWithCredentials( this.withCredentials );
  16550. loader.load( url, function ( text ) {
  16551. var json = JSON.parse( text );
  16552. var metadata = json.metadata;
  16553. if ( metadata !== undefined ) {
  16554. var type = metadata.type;
  16555. if ( type !== undefined ) {
  16556. if ( type.toLowerCase() === 'object' ) {
  16557. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  16558. return;
  16559. }
  16560. if ( type.toLowerCase() === 'scene' ) {
  16561. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  16562. return;
  16563. }
  16564. }
  16565. }
  16566. var object = scope.parse( json, texturePath );
  16567. onLoad( object.geometry, object.materials );
  16568. }, onProgress, onError );
  16569. },
  16570. setTexturePath: function ( value ) {
  16571. this.texturePath = value;
  16572. },
  16573. parse: function ( json, texturePath ) {
  16574. var geometry = new Geometry(),
  16575. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  16576. parseModel( scale );
  16577. parseSkin();
  16578. parseMorphing( scale );
  16579. parseAnimations();
  16580. geometry.computeFaceNormals();
  16581. geometry.computeBoundingSphere();
  16582. function parseModel( scale ) {
  16583. function isBitSet( value, position ) {
  16584. return value & ( 1 << position );
  16585. }
  16586. var i, j, fi,
  16587. offset, zLength,
  16588. colorIndex, normalIndex, uvIndex, materialIndex,
  16589. type,
  16590. isQuad,
  16591. hasMaterial,
  16592. hasFaceVertexUv,
  16593. hasFaceNormal, hasFaceVertexNormal,
  16594. hasFaceColor, hasFaceVertexColor,
  16595. vertex, face, faceA, faceB, hex, normal,
  16596. uvLayer, uv, u, v,
  16597. faces = json.faces,
  16598. vertices = json.vertices,
  16599. normals = json.normals,
  16600. colors = json.colors,
  16601. nUvLayers = 0;
  16602. if ( json.uvs !== undefined ) {
  16603. // disregard empty arrays
  16604. for ( i = 0; i < json.uvs.length; i ++ ) {
  16605. if ( json.uvs[ i ].length ) nUvLayers ++;
  16606. }
  16607. for ( i = 0; i < nUvLayers; i ++ ) {
  16608. geometry.faceVertexUvs[ i ] = [];
  16609. }
  16610. }
  16611. offset = 0;
  16612. zLength = vertices.length;
  16613. while ( offset < zLength ) {
  16614. vertex = new Vector3();
  16615. vertex.x = vertices[ offset ++ ] * scale;
  16616. vertex.y = vertices[ offset ++ ] * scale;
  16617. vertex.z = vertices[ offset ++ ] * scale;
  16618. geometry.vertices.push( vertex );
  16619. }
  16620. offset = 0;
  16621. zLength = faces.length;
  16622. while ( offset < zLength ) {
  16623. type = faces[ offset ++ ];
  16624. isQuad = isBitSet( type, 0 );
  16625. hasMaterial = isBitSet( type, 1 );
  16626. hasFaceVertexUv = isBitSet( type, 3 );
  16627. hasFaceNormal = isBitSet( type, 4 );
  16628. hasFaceVertexNormal = isBitSet( type, 5 );
  16629. hasFaceColor = isBitSet( type, 6 );
  16630. hasFaceVertexColor = isBitSet( type, 7 );
  16631. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  16632. if ( isQuad ) {
  16633. faceA = new Face3();
  16634. faceA.a = faces[ offset ];
  16635. faceA.b = faces[ offset + 1 ];
  16636. faceA.c = faces[ offset + 3 ];
  16637. faceB = new Face3();
  16638. faceB.a = faces[ offset + 1 ];
  16639. faceB.b = faces[ offset + 2 ];
  16640. faceB.c = faces[ offset + 3 ];
  16641. offset += 4;
  16642. if ( hasMaterial ) {
  16643. materialIndex = faces[ offset ++ ];
  16644. faceA.materialIndex = materialIndex;
  16645. faceB.materialIndex = materialIndex;
  16646. }
  16647. // to get face <=> uv index correspondence
  16648. fi = geometry.faces.length;
  16649. if ( hasFaceVertexUv ) {
  16650. for ( i = 0; i < nUvLayers; i ++ ) {
  16651. uvLayer = json.uvs[ i ];
  16652. geometry.faceVertexUvs[ i ][ fi ] = [];
  16653. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  16654. for ( j = 0; j < 4; j ++ ) {
  16655. uvIndex = faces[ offset ++ ];
  16656. u = uvLayer[ uvIndex * 2 ];
  16657. v = uvLayer[ uvIndex * 2 + 1 ];
  16658. uv = new Vector2( u, v );
  16659. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16660. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  16661. }
  16662. }
  16663. }
  16664. if ( hasFaceNormal ) {
  16665. normalIndex = faces[ offset ++ ] * 3;
  16666. faceA.normal.set(
  16667. normals[ normalIndex ++ ],
  16668. normals[ normalIndex ++ ],
  16669. normals[ normalIndex ]
  16670. );
  16671. faceB.normal.copy( faceA.normal );
  16672. }
  16673. if ( hasFaceVertexNormal ) {
  16674. for ( i = 0; i < 4; i ++ ) {
  16675. normalIndex = faces[ offset ++ ] * 3;
  16676. normal = new Vector3(
  16677. normals[ normalIndex ++ ],
  16678. normals[ normalIndex ++ ],
  16679. normals[ normalIndex ]
  16680. );
  16681. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  16682. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  16683. }
  16684. }
  16685. if ( hasFaceColor ) {
  16686. colorIndex = faces[ offset ++ ];
  16687. hex = colors[ colorIndex ];
  16688. faceA.color.setHex( hex );
  16689. faceB.color.setHex( hex );
  16690. }
  16691. if ( hasFaceVertexColor ) {
  16692. for ( i = 0; i < 4; i ++ ) {
  16693. colorIndex = faces[ offset ++ ];
  16694. hex = colors[ colorIndex ];
  16695. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  16696. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  16697. }
  16698. }
  16699. geometry.faces.push( faceA );
  16700. geometry.faces.push( faceB );
  16701. } else {
  16702. face = new Face3();
  16703. face.a = faces[ offset ++ ];
  16704. face.b = faces[ offset ++ ];
  16705. face.c = faces[ offset ++ ];
  16706. if ( hasMaterial ) {
  16707. materialIndex = faces[ offset ++ ];
  16708. face.materialIndex = materialIndex;
  16709. }
  16710. // to get face <=> uv index correspondence
  16711. fi = geometry.faces.length;
  16712. if ( hasFaceVertexUv ) {
  16713. for ( i = 0; i < nUvLayers; i ++ ) {
  16714. uvLayer = json.uvs[ i ];
  16715. geometry.faceVertexUvs[ i ][ fi ] = [];
  16716. for ( j = 0; j < 3; j ++ ) {
  16717. uvIndex = faces[ offset ++ ];
  16718. u = uvLayer[ uvIndex * 2 ];
  16719. v = uvLayer[ uvIndex * 2 + 1 ];
  16720. uv = new Vector2( u, v );
  16721. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16722. }
  16723. }
  16724. }
  16725. if ( hasFaceNormal ) {
  16726. normalIndex = faces[ offset ++ ] * 3;
  16727. face.normal.set(
  16728. normals[ normalIndex ++ ],
  16729. normals[ normalIndex ++ ],
  16730. normals[ normalIndex ]
  16731. );
  16732. }
  16733. if ( hasFaceVertexNormal ) {
  16734. for ( i = 0; i < 3; i ++ ) {
  16735. normalIndex = faces[ offset ++ ] * 3;
  16736. normal = new Vector3(
  16737. normals[ normalIndex ++ ],
  16738. normals[ normalIndex ++ ],
  16739. normals[ normalIndex ]
  16740. );
  16741. face.vertexNormals.push( normal );
  16742. }
  16743. }
  16744. if ( hasFaceColor ) {
  16745. colorIndex = faces[ offset ++ ];
  16746. face.color.setHex( colors[ colorIndex ] );
  16747. }
  16748. if ( hasFaceVertexColor ) {
  16749. for ( i = 0; i < 3; i ++ ) {
  16750. colorIndex = faces[ offset ++ ];
  16751. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  16752. }
  16753. }
  16754. geometry.faces.push( face );
  16755. }
  16756. }
  16757. }
  16758. function parseSkin() {
  16759. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  16760. if ( json.skinWeights ) {
  16761. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  16762. var x = json.skinWeights[ i ];
  16763. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  16764. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  16765. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  16766. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  16767. }
  16768. }
  16769. if ( json.skinIndices ) {
  16770. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  16771. var a = json.skinIndices[ i ];
  16772. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  16773. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  16774. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  16775. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  16776. }
  16777. }
  16778. geometry.bones = json.bones;
  16779. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  16780. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  16781. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  16782. }
  16783. }
  16784. function parseMorphing( scale ) {
  16785. if ( json.morphTargets !== undefined ) {
  16786. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  16787. geometry.morphTargets[ i ] = {};
  16788. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  16789. geometry.morphTargets[ i ].vertices = [];
  16790. var dstVertices = geometry.morphTargets[ i ].vertices;
  16791. var srcVertices = json.morphTargets[ i ].vertices;
  16792. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  16793. var vertex = new Vector3();
  16794. vertex.x = srcVertices[ v ] * scale;
  16795. vertex.y = srcVertices[ v + 1 ] * scale;
  16796. vertex.z = srcVertices[ v + 2 ] * scale;
  16797. dstVertices.push( vertex );
  16798. }
  16799. }
  16800. }
  16801. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  16802. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  16803. var faces = geometry.faces;
  16804. var morphColors = json.morphColors[ 0 ].colors;
  16805. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16806. faces[ i ].color.fromArray( morphColors, i * 3 );
  16807. }
  16808. }
  16809. }
  16810. function parseAnimations() {
  16811. var outputAnimations = [];
  16812. // parse old style Bone/Hierarchy animations
  16813. var animations = [];
  16814. if ( json.animation !== undefined ) {
  16815. animations.push( json.animation );
  16816. }
  16817. if ( json.animations !== undefined ) {
  16818. if ( json.animations.length ) {
  16819. animations = animations.concat( json.animations );
  16820. } else {
  16821. animations.push( json.animations );
  16822. }
  16823. }
  16824. for ( var i = 0; i < animations.length; i ++ ) {
  16825. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  16826. if ( clip ) outputAnimations.push( clip );
  16827. }
  16828. // parse implicit morph animations
  16829. if ( geometry.morphTargets ) {
  16830. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  16831. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  16832. outputAnimations = outputAnimations.concat( morphAnimationClips );
  16833. }
  16834. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  16835. }
  16836. if ( json.materials === undefined || json.materials.length === 0 ) {
  16837. return { geometry: geometry };
  16838. } else {
  16839. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  16840. return { geometry: geometry, materials: materials };
  16841. }
  16842. }
  16843. } );
  16844. /**
  16845. * @author mrdoob / http://mrdoob.com/
  16846. */
  16847. function ObjectLoader ( manager ) {
  16848. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16849. this.texturePath = '';
  16850. }
  16851. Object.assign( ObjectLoader.prototype, {
  16852. load: function ( url, onLoad, onProgress, onError ) {
  16853. if ( this.texturePath === '' ) {
  16854. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  16855. }
  16856. var scope = this;
  16857. var loader = new XHRLoader( scope.manager );
  16858. loader.load( url, function ( text ) {
  16859. scope.parse( JSON.parse( text ), onLoad );
  16860. }, onProgress, onError );
  16861. },
  16862. setTexturePath: function ( value ) {
  16863. this.texturePath = value;
  16864. },
  16865. setCrossOrigin: function ( value ) {
  16866. this.crossOrigin = value;
  16867. },
  16868. parse: function ( json, onLoad ) {
  16869. var geometries = this.parseGeometries( json.geometries );
  16870. var images = this.parseImages( json.images, function () {
  16871. if ( onLoad !== undefined ) onLoad( object );
  16872. } );
  16873. var textures = this.parseTextures( json.textures, images );
  16874. var materials = this.parseMaterials( json.materials, textures );
  16875. var object = this.parseObject( json.object, geometries, materials );
  16876. if ( json.animations ) {
  16877. object.animations = this.parseAnimations( json.animations );
  16878. }
  16879. if ( json.images === undefined || json.images.length === 0 ) {
  16880. if ( onLoad !== undefined ) onLoad( object );
  16881. }
  16882. return object;
  16883. },
  16884. parseGeometries: function ( json ) {
  16885. var geometries = {};
  16886. if ( json !== undefined ) {
  16887. var geometryLoader = new JSONLoader();
  16888. var bufferGeometryLoader = new BufferGeometryLoader();
  16889. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16890. var geometry;
  16891. var data = json[ i ];
  16892. switch ( data.type ) {
  16893. case 'PlaneGeometry':
  16894. case 'PlaneBufferGeometry':
  16895. geometry = new THREE[ data.type ](
  16896. data.width,
  16897. data.height,
  16898. data.widthSegments,
  16899. data.heightSegments
  16900. );
  16901. break;
  16902. case 'BoxGeometry':
  16903. case 'BoxBufferGeometry':
  16904. case 'CubeGeometry': // backwards compatible
  16905. geometry = new THREE[ data.type ](
  16906. data.width,
  16907. data.height,
  16908. data.depth,
  16909. data.widthSegments,
  16910. data.heightSegments,
  16911. data.depthSegments
  16912. );
  16913. break;
  16914. case 'CircleGeometry':
  16915. case 'CircleBufferGeometry':
  16916. geometry = new THREE[ data.type ](
  16917. data.radius,
  16918. data.segments,
  16919. data.thetaStart,
  16920. data.thetaLength
  16921. );
  16922. break;
  16923. case 'CylinderGeometry':
  16924. case 'CylinderBufferGeometry':
  16925. geometry = new THREE[ data.type ](
  16926. data.radiusTop,
  16927. data.radiusBottom,
  16928. data.height,
  16929. data.radialSegments,
  16930. data.heightSegments,
  16931. data.openEnded,
  16932. data.thetaStart,
  16933. data.thetaLength
  16934. );
  16935. break;
  16936. case 'ConeGeometry':
  16937. case 'ConeBufferGeometry':
  16938. geometry = new THREE [ data.type ](
  16939. data.radius,
  16940. data.height,
  16941. data.radialSegments,
  16942. data.heightSegments,
  16943. data.openEnded,
  16944. data.thetaStart,
  16945. data.thetaLength
  16946. );
  16947. break;
  16948. case 'SphereGeometry':
  16949. case 'SphereBufferGeometry':
  16950. geometry = new THREE[ data.type ](
  16951. data.radius,
  16952. data.widthSegments,
  16953. data.heightSegments,
  16954. data.phiStart,
  16955. data.phiLength,
  16956. data.thetaStart,
  16957. data.thetaLength
  16958. );
  16959. break;
  16960. case 'DodecahedronGeometry':
  16961. case 'IcosahedronGeometry':
  16962. case 'OctahedronGeometry':
  16963. case 'TetrahedronGeometry':
  16964. geometry = new THREE[ data.type ](
  16965. data.radius,
  16966. data.detail
  16967. );
  16968. break;
  16969. case 'RingGeometry':
  16970. case 'RingBufferGeometry':
  16971. geometry = new THREE[ data.type ](
  16972. data.innerRadius,
  16973. data.outerRadius,
  16974. data.thetaSegments,
  16975. data.phiSegments,
  16976. data.thetaStart,
  16977. data.thetaLength
  16978. );
  16979. break;
  16980. case 'TorusGeometry':
  16981. case 'TorusBufferGeometry':
  16982. geometry = new THREE[ data.type ](
  16983. data.radius,
  16984. data.tube,
  16985. data.radialSegments,
  16986. data.tubularSegments,
  16987. data.arc
  16988. );
  16989. break;
  16990. case 'TorusKnotGeometry':
  16991. case 'TorusKnotBufferGeometry':
  16992. geometry = new THREE[ data.type ](
  16993. data.radius,
  16994. data.tube,
  16995. data.tubularSegments,
  16996. data.radialSegments,
  16997. data.p,
  16998. data.q
  16999. );
  17000. break;
  17001. case 'LatheGeometry':
  17002. case 'LatheBufferGeometry':
  17003. geometry = new THREE[ data.type ](
  17004. data.points,
  17005. data.segments,
  17006. data.phiStart,
  17007. data.phiLength
  17008. );
  17009. break;
  17010. case 'BufferGeometry':
  17011. geometry = bufferGeometryLoader.parse( data );
  17012. break;
  17013. case 'Geometry':
  17014. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  17015. break;
  17016. default:
  17017. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  17018. continue;
  17019. }
  17020. geometry.uuid = data.uuid;
  17021. if ( data.name !== undefined ) geometry.name = data.name;
  17022. geometries[ data.uuid ] = geometry;
  17023. }
  17024. }
  17025. return geometries;
  17026. },
  17027. parseMaterials: function ( json, textures ) {
  17028. var materials = {};
  17029. if ( json !== undefined ) {
  17030. var loader = new MaterialLoader();
  17031. loader.setTextures( textures );
  17032. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17033. var material = loader.parse( json[ i ] );
  17034. materials[ material.uuid ] = material;
  17035. }
  17036. }
  17037. return materials;
  17038. },
  17039. parseAnimations: function ( json ) {
  17040. var animations = [];
  17041. for ( var i = 0; i < json.length; i ++ ) {
  17042. var clip = AnimationClip.parse( json[ i ] );
  17043. animations.push( clip );
  17044. }
  17045. return animations;
  17046. },
  17047. parseImages: function ( json, onLoad ) {
  17048. var scope = this;
  17049. var images = {};
  17050. function loadImage( url ) {
  17051. scope.manager.itemStart( url );
  17052. return loader.load( url, function () {
  17053. scope.manager.itemEnd( url );
  17054. }, undefined, function () {
  17055. scope.manager.itemError( url );
  17056. } );
  17057. }
  17058. if ( json !== undefined && json.length > 0 ) {
  17059. var manager = new LoadingManager( onLoad );
  17060. var loader = new ImageLoader( manager );
  17061. loader.setCrossOrigin( this.crossOrigin );
  17062. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17063. var image = json[ i ];
  17064. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  17065. images[ image.uuid ] = loadImage( path );
  17066. }
  17067. }
  17068. return images;
  17069. },
  17070. parseTextures: function ( json, images ) {
  17071. function parseConstant( value ) {
  17072. if ( typeof( value ) === 'number' ) return value;
  17073. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17074. return THREE[ value ];
  17075. }
  17076. var textures = {};
  17077. if ( json !== undefined ) {
  17078. for ( var i = 0, l = json.length; i < l; i ++ ) {
  17079. var data = json[ i ];
  17080. if ( data.image === undefined ) {
  17081. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17082. }
  17083. if ( images[ data.image ] === undefined ) {
  17084. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17085. }
  17086. var texture = new Texture( images[ data.image ] );
  17087. texture.needsUpdate = true;
  17088. texture.uuid = data.uuid;
  17089. if ( data.name !== undefined ) texture.name = data.name;
  17090. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  17091. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17092. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17093. if ( data.wrap !== undefined ) {
  17094. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  17095. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  17096. }
  17097. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  17098. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  17099. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17100. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17101. textures[ data.uuid ] = texture;
  17102. }
  17103. }
  17104. return textures;
  17105. },
  17106. parseObject: function () {
  17107. var matrix = new Matrix4();
  17108. return function parseObject( data, geometries, materials ) {
  17109. var object;
  17110. function getGeometry( name ) {
  17111. if ( geometries[ name ] === undefined ) {
  17112. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17113. }
  17114. return geometries[ name ];
  17115. }
  17116. function getMaterial( name ) {
  17117. if ( name === undefined ) return undefined;
  17118. if ( materials[ name ] === undefined ) {
  17119. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17120. }
  17121. return materials[ name ];
  17122. }
  17123. switch ( data.type ) {
  17124. case 'Scene':
  17125. object = new Scene();
  17126. if ( data.background !== undefined ) {
  17127. if ( Number.isInteger( data.background ) ) {
  17128. object.background = new THREE.Color( data.background );
  17129. }
  17130. }
  17131. if ( data.fog !== undefined ) {
  17132. if ( data.fog.type === 'Fog' ) {
  17133. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17134. } else if ( data.fog.type === 'FogExp2' ) {
  17135. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17136. }
  17137. }
  17138. break;
  17139. case 'PerspectiveCamera':
  17140. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17141. if ( data.focus !== undefined ) object.focus = data.focus;
  17142. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17143. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17144. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17145. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17146. break;
  17147. case 'OrthographicCamera':
  17148. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17149. break;
  17150. case 'AmbientLight':
  17151. object = new AmbientLight( data.color, data.intensity );
  17152. break;
  17153. case 'DirectionalLight':
  17154. object = new DirectionalLight( data.color, data.intensity );
  17155. break;
  17156. case 'PointLight':
  17157. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17158. break;
  17159. case 'SpotLight':
  17160. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17161. break;
  17162. case 'HemisphereLight':
  17163. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17164. break;
  17165. case 'Mesh':
  17166. var geometry = getGeometry( data.geometry );
  17167. var material = getMaterial( data.material );
  17168. if ( geometry.bones && geometry.bones.length > 0 ) {
  17169. object = new SkinnedMesh( geometry, material );
  17170. } else {
  17171. object = new Mesh( geometry, material );
  17172. }
  17173. break;
  17174. case 'LOD':
  17175. object = new LOD();
  17176. break;
  17177. case 'Line':
  17178. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  17179. break;
  17180. case 'LineSegments':
  17181. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17182. break;
  17183. case 'PointCloud':
  17184. case 'Points':
  17185. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17186. break;
  17187. case 'Sprite':
  17188. object = new Sprite( getMaterial( data.material ) );
  17189. break;
  17190. case 'Group':
  17191. object = new Group();
  17192. break;
  17193. default:
  17194. object = new Object3D();
  17195. }
  17196. object.uuid = data.uuid;
  17197. if ( data.name !== undefined ) object.name = data.name;
  17198. if ( data.matrix !== undefined ) {
  17199. matrix.fromArray( data.matrix );
  17200. matrix.decompose( object.position, object.quaternion, object.scale );
  17201. } else {
  17202. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17203. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17204. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17205. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17206. }
  17207. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17208. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17209. if ( data.shadow ) {
  17210. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17211. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17212. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17213. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17214. }
  17215. if ( data.visible !== undefined ) object.visible = data.visible;
  17216. if ( data.userData !== undefined ) object.userData = data.userData;
  17217. if ( data.children !== undefined ) {
  17218. for ( var child in data.children ) {
  17219. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  17220. }
  17221. }
  17222. if ( data.type === 'LOD' ) {
  17223. var levels = data.levels;
  17224. for ( var l = 0; l < levels.length; l ++ ) {
  17225. var level = levels[ l ];
  17226. var child = object.getObjectByProperty( 'uuid', level.object );
  17227. if ( child !== undefined ) {
  17228. object.addLevel( child, level.distance );
  17229. }
  17230. }
  17231. }
  17232. return object;
  17233. };
  17234. }()
  17235. } );
  17236. /**
  17237. * @author zz85 / http://www.lab4games.net/zz85/blog
  17238. */
  17239. exports.ShapeUtils = {
  17240. // calculate area of the contour polygon
  17241. area: function ( contour ) {
  17242. var n = contour.length;
  17243. var a = 0.0;
  17244. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  17245. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17246. }
  17247. return a * 0.5;
  17248. },
  17249. triangulate: ( function () {
  17250. /**
  17251. * This code is a quick port of code written in C++ which was submitted to
  17252. * flipcode.com by John W. Ratcliff // July 22, 2000
  17253. * See original code and more information here:
  17254. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17255. *
  17256. * ported to actionscript by Zevan Rosser
  17257. * www.actionsnippet.com
  17258. *
  17259. * ported to javascript by Joshua Koo
  17260. * http://www.lab4games.net/zz85/blog
  17261. *
  17262. */
  17263. function snip( contour, u, v, w, n, verts ) {
  17264. var p;
  17265. var ax, ay, bx, by;
  17266. var cx, cy, px, py;
  17267. ax = contour[ verts[ u ] ].x;
  17268. ay = contour[ verts[ u ] ].y;
  17269. bx = contour[ verts[ v ] ].x;
  17270. by = contour[ verts[ v ] ].y;
  17271. cx = contour[ verts[ w ] ].x;
  17272. cy = contour[ verts[ w ] ].y;
  17273. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  17274. var aX, aY, bX, bY, cX, cY;
  17275. var apx, apy, bpx, bpy, cpx, cpy;
  17276. var cCROSSap, bCROSScp, aCROSSbp;
  17277. aX = cx - bx; aY = cy - by;
  17278. bX = ax - cx; bY = ay - cy;
  17279. cX = bx - ax; cY = by - ay;
  17280. for ( p = 0; p < n; p ++ ) {
  17281. px = contour[ verts[ p ] ].x;
  17282. py = contour[ verts[ p ] ].y;
  17283. if ( ( ( px === ax ) && ( py === ay ) ) ||
  17284. ( ( px === bx ) && ( py === by ) ) ||
  17285. ( ( px === cx ) && ( py === cy ) ) ) continue;
  17286. apx = px - ax; apy = py - ay;
  17287. bpx = px - bx; bpy = py - by;
  17288. cpx = px - cx; cpy = py - cy;
  17289. // see if p is inside triangle abc
  17290. aCROSSbp = aX * bpy - aY * bpx;
  17291. cCROSSap = cX * apy - cY * apx;
  17292. bCROSScp = bX * cpy - bY * cpx;
  17293. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  17294. }
  17295. return true;
  17296. }
  17297. // takes in an contour array and returns
  17298. return function triangulate( contour, indices ) {
  17299. var n = contour.length;
  17300. if ( n < 3 ) return null;
  17301. var result = [],
  17302. verts = [],
  17303. vertIndices = [];
  17304. /* we want a counter-clockwise polygon in verts */
  17305. var u, v, w;
  17306. if ( exports.ShapeUtils.area( contour ) > 0.0 ) {
  17307. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  17308. } else {
  17309. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  17310. }
  17311. var nv = n;
  17312. /* remove nv - 2 vertices, creating 1 triangle every time */
  17313. var count = 2 * nv; /* error detection */
  17314. for ( v = nv - 1; nv > 2; ) {
  17315. /* if we loop, it is probably a non-simple polygon */
  17316. if ( ( count -- ) <= 0 ) {
  17317. //** Triangulate: ERROR - probable bad polygon!
  17318. //throw ( "Warning, unable to triangulate polygon!" );
  17319. //return null;
  17320. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17321. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  17322. if ( indices ) return vertIndices;
  17323. return result;
  17324. }
  17325. /* three consecutive vertices in current polygon, <u,v,w> */
  17326. u = v; if ( nv <= u ) u = 0; /* previous */
  17327. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17328. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17329. if ( snip( contour, u, v, w, nv, verts ) ) {
  17330. var a, b, c, s, t;
  17331. /* true names of the vertices */
  17332. a = verts[ u ];
  17333. b = verts[ v ];
  17334. c = verts[ w ];
  17335. /* output Triangle */
  17336. result.push( [ contour[ a ],
  17337. contour[ b ],
  17338. contour[ c ] ] );
  17339. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17340. /* remove v from the remaining polygon */
  17341. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  17342. verts[ s ] = verts[ t ];
  17343. }
  17344. nv --;
  17345. /* reset error detection counter */
  17346. count = 2 * nv;
  17347. }
  17348. }
  17349. if ( indices ) return vertIndices;
  17350. return result;
  17351. }
  17352. } )(),
  17353. triangulateShape: function ( contour, holes ) {
  17354. function removeDupEndPts(points) {
  17355. var l = points.length;
  17356. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17357. points.pop();
  17358. }
  17359. }
  17360. removeDupEndPts( contour );
  17361. holes.forEach( removeDupEndPts );
  17362. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17363. // inOtherPt needs to be collinear to the inSegment
  17364. if ( inSegPt1.x !== inSegPt2.x ) {
  17365. if ( inSegPt1.x < inSegPt2.x ) {
  17366. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17367. } else {
  17368. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17369. }
  17370. } else {
  17371. if ( inSegPt1.y < inSegPt2.y ) {
  17372. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17373. } else {
  17374. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17375. }
  17376. }
  17377. }
  17378. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17379. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17380. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17381. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17382. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17383. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17384. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17385. if ( Math.abs( limit ) > Number.EPSILON ) {
  17386. // not parallel
  17387. var perpSeg2;
  17388. if ( limit > 0 ) {
  17389. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17390. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17391. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17392. } else {
  17393. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17394. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17395. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17396. }
  17397. // i.e. to reduce rounding errors
  17398. // intersection at endpoint of segment#1?
  17399. if ( perpSeg2 === 0 ) {
  17400. if ( ( inExcludeAdjacentSegs ) &&
  17401. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17402. return [ inSeg1Pt1 ];
  17403. }
  17404. if ( perpSeg2 === limit ) {
  17405. if ( ( inExcludeAdjacentSegs ) &&
  17406. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17407. return [ inSeg1Pt2 ];
  17408. }
  17409. // intersection at endpoint of segment#2?
  17410. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  17411. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  17412. // return real intersection point
  17413. var factorSeg1 = perpSeg2 / limit;
  17414. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17415. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17416. } else {
  17417. // parallel or collinear
  17418. if ( ( perpSeg1 !== 0 ) ||
  17419. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  17420. // they are collinear or degenerate
  17421. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  17422. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  17423. // both segments are points
  17424. if ( seg1Pt && seg2Pt ) {
  17425. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  17426. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  17427. return [ inSeg1Pt1 ]; // they are the same point
  17428. }
  17429. // segment#1 is a single point
  17430. if ( seg1Pt ) {
  17431. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17432. return [ inSeg1Pt1 ];
  17433. }
  17434. // segment#2 is a single point
  17435. if ( seg2Pt ) {
  17436. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17437. return [ inSeg2Pt1 ];
  17438. }
  17439. // they are collinear segments, which might overlap
  17440. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17441. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17442. if ( seg1dx !== 0 ) {
  17443. // the segments are NOT on a vertical line
  17444. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17445. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17446. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17447. } else {
  17448. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17449. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17450. }
  17451. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17452. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17453. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17454. } else {
  17455. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17456. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17457. }
  17458. } else {
  17459. // the segments are on a vertical line
  17460. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17461. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17462. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17463. } else {
  17464. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17465. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17466. }
  17467. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17468. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17469. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17470. } else {
  17471. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17472. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17473. }
  17474. }
  17475. if ( seg1minVal <= seg2minVal ) {
  17476. if ( seg1maxVal < seg2minVal ) return [];
  17477. if ( seg1maxVal === seg2minVal ) {
  17478. if ( inExcludeAdjacentSegs ) return [];
  17479. return [ seg2min ];
  17480. }
  17481. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17482. return [ seg2min, seg2max ];
  17483. } else {
  17484. if ( seg1minVal > seg2maxVal ) return [];
  17485. if ( seg1minVal === seg2maxVal ) {
  17486. if ( inExcludeAdjacentSegs ) return [];
  17487. return [ seg1min ];
  17488. }
  17489. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17490. return [ seg1min, seg2max ];
  17491. }
  17492. }
  17493. }
  17494. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17495. // The order of legs is important
  17496. // translation of all points, so that Vertex is at (0,0)
  17497. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17498. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17499. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17500. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17501. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17502. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17503. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  17504. // angle != 180 deg.
  17505. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17506. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17507. if ( from2toAngle > 0 ) {
  17508. // main angle < 180 deg.
  17509. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17510. } else {
  17511. // main angle > 180 deg.
  17512. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17513. }
  17514. } else {
  17515. // angle == 180 deg.
  17516. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17517. return ( from2otherAngle > 0 );
  17518. }
  17519. }
  17520. function removeHoles( contour, holes ) {
  17521. var shape = contour.concat(); // work on this shape
  17522. var hole;
  17523. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17524. // Check if hole point lies within angle around shape point
  17525. var lastShapeIdx = shape.length - 1;
  17526. var prevShapeIdx = inShapeIdx - 1;
  17527. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17528. var nextShapeIdx = inShapeIdx + 1;
  17529. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17530. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  17531. if ( ! insideAngle ) {
  17532. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17533. return false;
  17534. }
  17535. // Check if shape point lies within angle around hole point
  17536. var lastHoleIdx = hole.length - 1;
  17537. var prevHoleIdx = inHoleIdx - 1;
  17538. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17539. var nextHoleIdx = inHoleIdx + 1;
  17540. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17541. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  17542. if ( ! insideAngle ) {
  17543. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17544. return false;
  17545. }
  17546. return true;
  17547. }
  17548. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17549. // checks for intersections with shape edges
  17550. var sIdx, nextIdx, intersection;
  17551. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17552. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17553. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  17554. if ( intersection.length > 0 ) return true;
  17555. }
  17556. return false;
  17557. }
  17558. var indepHoles = [];
  17559. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17560. // checks for intersections with hole edges
  17561. var ihIdx, chkHole,
  17562. hIdx, nextIdx, intersection;
  17563. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17564. chkHole = holes[ indepHoles[ ihIdx ]];
  17565. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17566. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17567. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  17568. if ( intersection.length > 0 ) return true;
  17569. }
  17570. }
  17571. return false;
  17572. }
  17573. var holeIndex, shapeIndex,
  17574. shapePt, holePt,
  17575. holeIdx, cutKey, failedCuts = [],
  17576. tmpShape1, tmpShape2,
  17577. tmpHole1, tmpHole2;
  17578. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17579. indepHoles.push( h );
  17580. }
  17581. var minShapeIndex = 0;
  17582. var counter = indepHoles.length * 2;
  17583. while ( indepHoles.length > 0 ) {
  17584. counter --;
  17585. if ( counter < 0 ) {
  17586. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17587. break;
  17588. }
  17589. // search for shape-vertex and hole-vertex,
  17590. // which can be connected without intersections
  17591. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17592. shapePt = shape[ shapeIndex ];
  17593. holeIndex = - 1;
  17594. // search for hole which can be reached without intersections
  17595. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17596. holeIdx = indepHoles[ h ];
  17597. // prevent multiple checks
  17598. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17599. if ( failedCuts[ cutKey ] !== undefined ) continue;
  17600. hole = holes[ holeIdx ];
  17601. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17602. holePt = hole[ h2 ];
  17603. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17604. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17605. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17606. holeIndex = h2;
  17607. indepHoles.splice( h, 1 );
  17608. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17609. tmpShape2 = shape.slice( shapeIndex );
  17610. tmpHole1 = hole.slice( holeIndex );
  17611. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17612. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17613. minShapeIndex = shapeIndex;
  17614. // Debug only, to show the selected cuts
  17615. // glob_CutLines.push( [ shapePt, holePt ] );
  17616. break;
  17617. }
  17618. if ( holeIndex >= 0 ) break; // hole-vertex found
  17619. failedCuts[ cutKey ] = true; // remember failure
  17620. }
  17621. if ( holeIndex >= 0 ) break; // hole-vertex found
  17622. }
  17623. }
  17624. return shape; /* shape with no holes */
  17625. }
  17626. var i, il, f, face,
  17627. key, index,
  17628. allPointsMap = {};
  17629. // 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.
  17630. var allpoints = contour.concat();
  17631. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17632. Array.prototype.push.apply( allpoints, holes[ h ] );
  17633. }
  17634. //console.log( "allpoints",allpoints, allpoints.length );
  17635. // prepare all points map
  17636. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17637. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17638. if ( allPointsMap[ key ] !== undefined ) {
  17639. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  17640. }
  17641. allPointsMap[ key ] = i;
  17642. }
  17643. // remove holes by cutting paths to holes and adding them to the shape
  17644. var shapeWithoutHoles = removeHoles( contour, holes );
  17645. var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17646. //console.log( "triangles",triangles, triangles.length );
  17647. // check all face vertices against all points map
  17648. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17649. face = triangles[ i ];
  17650. for ( f = 0; f < 3; f ++ ) {
  17651. key = face[ f ].x + ":" + face[ f ].y;
  17652. index = allPointsMap[ key ];
  17653. if ( index !== undefined ) {
  17654. face[ f ] = index;
  17655. }
  17656. }
  17657. }
  17658. return triangles.concat();
  17659. },
  17660. isClockWise: function ( pts ) {
  17661. return exports.ShapeUtils.area( pts ) < 0;
  17662. },
  17663. // Bezier Curves formulas obtained from
  17664. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17665. // Quad Bezier Functions
  17666. b2: ( function () {
  17667. function b2p0( t, p ) {
  17668. var k = 1 - t;
  17669. return k * k * p;
  17670. }
  17671. function b2p1( t, p ) {
  17672. return 2 * ( 1 - t ) * t * p;
  17673. }
  17674. function b2p2( t, p ) {
  17675. return t * t * p;
  17676. }
  17677. return function b2( t, p0, p1, p2 ) {
  17678. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  17679. };
  17680. } )(),
  17681. // Cubic Bezier Functions
  17682. b3: ( function () {
  17683. function b3p0( t, p ) {
  17684. var k = 1 - t;
  17685. return k * k * k * p;
  17686. }
  17687. function b3p1( t, p ) {
  17688. var k = 1 - t;
  17689. return 3 * k * k * t * p;
  17690. }
  17691. function b3p2( t, p ) {
  17692. var k = 1 - t;
  17693. return 3 * k * t * t * p;
  17694. }
  17695. function b3p3( t, p ) {
  17696. return t * t * t * p;
  17697. }
  17698. return function b3( t, p0, p1, p2, p3 ) {
  17699. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  17700. };
  17701. } )()
  17702. };
  17703. /**
  17704. * @author zz85 / http://www.lab4games.net/zz85/blog
  17705. * Extensible curve object
  17706. *
  17707. * Some common of Curve methods
  17708. * .getPoint(t), getTangent(t)
  17709. * .getPointAt(u), getTangentAt(u)
  17710. * .getPoints(), .getSpacedPoints()
  17711. * .getLength()
  17712. * .updateArcLengths()
  17713. *
  17714. * This following classes subclasses THREE.Curve:
  17715. *
  17716. * -- 2d classes --
  17717. * THREE.LineCurve
  17718. * THREE.QuadraticBezierCurve
  17719. * THREE.CubicBezierCurve
  17720. * THREE.SplineCurve
  17721. * THREE.ArcCurve
  17722. * THREE.EllipseCurve
  17723. *
  17724. * -- 3d classes --
  17725. * THREE.LineCurve3
  17726. * THREE.QuadraticBezierCurve3
  17727. * THREE.CubicBezierCurve3
  17728. * THREE.SplineCurve3
  17729. *
  17730. * A series of curves can be represented as a THREE.CurvePath
  17731. *
  17732. **/
  17733. /**************************************************************
  17734. * Abstract Curve base class
  17735. **************************************************************/
  17736. function Curve() {}
  17737. Curve.prototype = {
  17738. constructor: Curve,
  17739. // Virtual base class method to overwrite and implement in subclasses
  17740. // - t [0 .. 1]
  17741. getPoint: function ( t ) {
  17742. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  17743. return null;
  17744. },
  17745. // Get point at relative position in curve according to arc length
  17746. // - u [0 .. 1]
  17747. getPointAt: function ( u ) {
  17748. var t = this.getUtoTmapping( u );
  17749. return this.getPoint( t );
  17750. },
  17751. // Get sequence of points using getPoint( t )
  17752. getPoints: function ( divisions ) {
  17753. if ( ! divisions ) divisions = 5;
  17754. var points = [];
  17755. for ( var d = 0; d <= divisions; d ++ ) {
  17756. points.push( this.getPoint( d / divisions ) );
  17757. }
  17758. return points;
  17759. },
  17760. // Get sequence of points using getPointAt( u )
  17761. getSpacedPoints: function ( divisions ) {
  17762. if ( ! divisions ) divisions = 5;
  17763. var points = [];
  17764. for ( var d = 0; d <= divisions; d ++ ) {
  17765. points.push( this.getPointAt( d / divisions ) );
  17766. }
  17767. return points;
  17768. },
  17769. // Get total curve arc length
  17770. getLength: function () {
  17771. var lengths = this.getLengths();
  17772. return lengths[ lengths.length - 1 ];
  17773. },
  17774. // Get list of cumulative segment lengths
  17775. getLengths: function ( divisions ) {
  17776. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  17777. if ( this.cacheArcLengths
  17778. && ( this.cacheArcLengths.length === divisions + 1 )
  17779. && ! this.needsUpdate ) {
  17780. //console.log( "cached", this.cacheArcLengths );
  17781. return this.cacheArcLengths;
  17782. }
  17783. this.needsUpdate = false;
  17784. var cache = [];
  17785. var current, last = this.getPoint( 0 );
  17786. var p, sum = 0;
  17787. cache.push( 0 );
  17788. for ( p = 1; p <= divisions; p ++ ) {
  17789. current = this.getPoint ( p / divisions );
  17790. sum += current.distanceTo( last );
  17791. cache.push( sum );
  17792. last = current;
  17793. }
  17794. this.cacheArcLengths = cache;
  17795. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17796. },
  17797. updateArcLengths: function() {
  17798. this.needsUpdate = true;
  17799. this.getLengths();
  17800. },
  17801. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17802. getUtoTmapping: function ( u, distance ) {
  17803. var arcLengths = this.getLengths();
  17804. var i = 0, il = arcLengths.length;
  17805. var targetArcLength; // The targeted u distance value to get
  17806. if ( distance ) {
  17807. targetArcLength = distance;
  17808. } else {
  17809. targetArcLength = u * arcLengths[ il - 1 ];
  17810. }
  17811. //var time = Date.now();
  17812. // binary search for the index with largest value smaller than target u distance
  17813. var low = 0, high = il - 1, comparison;
  17814. while ( low <= high ) {
  17815. 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
  17816. comparison = arcLengths[ i ] - targetArcLength;
  17817. if ( comparison < 0 ) {
  17818. low = i + 1;
  17819. } else if ( comparison > 0 ) {
  17820. high = i - 1;
  17821. } else {
  17822. high = i;
  17823. break;
  17824. // DONE
  17825. }
  17826. }
  17827. i = high;
  17828. //console.log('b' , i, low, high, Date.now()- time);
  17829. if ( arcLengths[ i ] === targetArcLength ) {
  17830. var t = i / ( il - 1 );
  17831. return t;
  17832. }
  17833. // we could get finer grain at lengths, or use simple interpolation between two points
  17834. var lengthBefore = arcLengths[ i ];
  17835. var lengthAfter = arcLengths[ i + 1 ];
  17836. var segmentLength = lengthAfter - lengthBefore;
  17837. // determine where we are between the 'before' and 'after' points
  17838. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17839. // add that fractional amount to t
  17840. var t = ( i + segmentFraction ) / ( il - 1 );
  17841. return t;
  17842. },
  17843. // Returns a unit vector tangent at t
  17844. // In case any sub curve does not implement its tangent derivation,
  17845. // 2 points a small delta apart will be used to find its gradient
  17846. // which seems to give a reasonable approximation
  17847. getTangent: function( t ) {
  17848. var delta = 0.0001;
  17849. var t1 = t - delta;
  17850. var t2 = t + delta;
  17851. // Capping in case of danger
  17852. if ( t1 < 0 ) t1 = 0;
  17853. if ( t2 > 1 ) t2 = 1;
  17854. var pt1 = this.getPoint( t1 );
  17855. var pt2 = this.getPoint( t2 );
  17856. var vec = pt2.clone().sub( pt1 );
  17857. return vec.normalize();
  17858. },
  17859. getTangentAt: function ( u ) {
  17860. var t = this.getUtoTmapping( u );
  17861. return this.getTangent( t );
  17862. }
  17863. };
  17864. // TODO: Transformation for Curves?
  17865. /**************************************************************
  17866. * 3D Curves
  17867. **************************************************************/
  17868. // A Factory method for creating new curve subclasses
  17869. Curve.create = function ( constructor, getPointFunc ) {
  17870. constructor.prototype = Object.create( Curve.prototype );
  17871. constructor.prototype.constructor = constructor;
  17872. constructor.prototype.getPoint = getPointFunc;
  17873. return constructor;
  17874. };
  17875. /**************************************************************
  17876. * Line
  17877. **************************************************************/
  17878. function LineCurve( v1, v2 ) {
  17879. this.v1 = v1;
  17880. this.v2 = v2;
  17881. }
  17882. LineCurve.prototype = Object.create( Curve.prototype );
  17883. LineCurve.prototype.constructor = LineCurve;
  17884. LineCurve.prototype.isLineCurve = true;
  17885. LineCurve.prototype.getPoint = function ( t ) {
  17886. if ( t === 1 ) {
  17887. return this.v2.clone();
  17888. }
  17889. var point = this.v2.clone().sub( this.v1 );
  17890. point.multiplyScalar( t ).add( this.v1 );
  17891. return point;
  17892. };
  17893. // Line curve is linear, so we can overwrite default getPointAt
  17894. LineCurve.prototype.getPointAt = function ( u ) {
  17895. return this.getPoint( u );
  17896. };
  17897. LineCurve.prototype.getTangent = function( t ) {
  17898. var tangent = this.v2.clone().sub( this.v1 );
  17899. return tangent.normalize();
  17900. };
  17901. /**
  17902. * @author zz85 / http://www.lab4games.net/zz85/blog
  17903. *
  17904. **/
  17905. /**************************************************************
  17906. * Curved Path - a curve path is simply a array of connected
  17907. * curves, but retains the api of a curve
  17908. **************************************************************/
  17909. function CurvePath() {
  17910. this.curves = [];
  17911. this.autoClose = false; // Automatically closes the path
  17912. }
  17913. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  17914. constructor: CurvePath,
  17915. add: function ( curve ) {
  17916. this.curves.push( curve );
  17917. },
  17918. closePath: function () {
  17919. // Add a line curve if start and end of lines are not connected
  17920. var startPoint = this.curves[ 0 ].getPoint( 0 );
  17921. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17922. if ( ! startPoint.equals( endPoint ) ) {
  17923. this.curves.push( new LineCurve( endPoint, startPoint ) );
  17924. }
  17925. },
  17926. // To get accurate point with reference to
  17927. // entire path distance at time t,
  17928. // following has to be done:
  17929. // 1. Length of each sub path have to be known
  17930. // 2. Locate and identify type of curve
  17931. // 3. Get t for the curve
  17932. // 4. Return curve.getPointAt(t')
  17933. getPoint: function ( t ) {
  17934. var d = t * this.getLength();
  17935. var curveLengths = this.getCurveLengths();
  17936. var i = 0;
  17937. // To think about boundaries points.
  17938. while ( i < curveLengths.length ) {
  17939. if ( curveLengths[ i ] >= d ) {
  17940. var diff = curveLengths[ i ] - d;
  17941. var curve = this.curves[ i ];
  17942. var segmentLength = curve.getLength();
  17943. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  17944. return curve.getPointAt( u );
  17945. }
  17946. i ++;
  17947. }
  17948. return null;
  17949. // loop where sum != 0, sum > d , sum+1 <d
  17950. },
  17951. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17952. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17953. // getPoint() depends on getLength
  17954. getLength: function () {
  17955. var lens = this.getCurveLengths();
  17956. return lens[ lens.length - 1 ];
  17957. },
  17958. // cacheLengths must be recalculated.
  17959. updateArcLengths: function () {
  17960. this.needsUpdate = true;
  17961. this.cacheLengths = null;
  17962. this.getLengths();
  17963. },
  17964. // Compute lengths and cache them
  17965. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17966. getCurveLengths: function () {
  17967. // We use cache values if curves and cache array are same length
  17968. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17969. return this.cacheLengths;
  17970. }
  17971. // Get length of sub-curve
  17972. // Push sums into cached array
  17973. var lengths = [], sums = 0;
  17974. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  17975. sums += this.curves[ i ].getLength();
  17976. lengths.push( sums );
  17977. }
  17978. this.cacheLengths = lengths;
  17979. return lengths;
  17980. },
  17981. getSpacedPoints: function ( divisions ) {
  17982. if ( ! divisions ) divisions = 40;
  17983. var points = [];
  17984. for ( var i = 0; i <= divisions; i ++ ) {
  17985. points.push( this.getPoint( i / divisions ) );
  17986. }
  17987. if ( this.autoClose ) {
  17988. points.push( points[ 0 ] );
  17989. }
  17990. return points;
  17991. },
  17992. getPoints: function ( divisions ) {
  17993. divisions = divisions || 12;
  17994. var points = [], last;
  17995. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  17996. var curve = curves[ i ];
  17997. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  17998. : (curve && curve.isLineCurve) ? 1
  17999. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  18000. : divisions;
  18001. var pts = curve.getPoints( resolution );
  18002. for ( var j = 0; j < pts.length; j++ ) {
  18003. var point = pts[ j ];
  18004. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  18005. points.push( point );
  18006. last = point;
  18007. }
  18008. }
  18009. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  18010. points.push( points[ 0 ] );
  18011. }
  18012. return points;
  18013. },
  18014. /**************************************************************
  18015. * Create Geometries Helpers
  18016. **************************************************************/
  18017. /// Generate geometry from path points (for Line or Points objects)
  18018. createPointsGeometry: function ( divisions ) {
  18019. var pts = this.getPoints( divisions );
  18020. return this.createGeometry( pts );
  18021. },
  18022. // Generate geometry from equidistant sampling along the path
  18023. createSpacedPointsGeometry: function ( divisions ) {
  18024. var pts = this.getSpacedPoints( divisions );
  18025. return this.createGeometry( pts );
  18026. },
  18027. createGeometry: function ( points ) {
  18028. var geometry = new Geometry();
  18029. for ( var i = 0, l = points.length; i < l; i ++ ) {
  18030. var point = points[ i ];
  18031. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  18032. }
  18033. return geometry;
  18034. }
  18035. } );
  18036. /**************************************************************
  18037. * Ellipse curve
  18038. **************************************************************/
  18039. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18040. this.aX = aX;
  18041. this.aY = aY;
  18042. this.xRadius = xRadius;
  18043. this.yRadius = yRadius;
  18044. this.aStartAngle = aStartAngle;
  18045. this.aEndAngle = aEndAngle;
  18046. this.aClockwise = aClockwise;
  18047. this.aRotation = aRotation || 0;
  18048. }
  18049. EllipseCurve.prototype = Object.create( Curve.prototype );
  18050. EllipseCurve.prototype.constructor = EllipseCurve;
  18051. EllipseCurve.prototype.isEllipseCurve = true;
  18052. EllipseCurve.prototype.getPoint = function( t ) {
  18053. var twoPi = Math.PI * 2;
  18054. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18055. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18056. // ensures that deltaAngle is 0 .. 2 PI
  18057. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18058. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18059. if ( deltaAngle < Number.EPSILON ) {
  18060. if ( samePoints ) {
  18061. deltaAngle = 0;
  18062. } else {
  18063. deltaAngle = twoPi;
  18064. }
  18065. }
  18066. if ( this.aClockwise === true && ! samePoints ) {
  18067. if ( deltaAngle === twoPi ) {
  18068. deltaAngle = - twoPi;
  18069. } else {
  18070. deltaAngle = deltaAngle - twoPi;
  18071. }
  18072. }
  18073. var angle = this.aStartAngle + t * deltaAngle;
  18074. var x = this.aX + this.xRadius * Math.cos( angle );
  18075. var y = this.aY + this.yRadius * Math.sin( angle );
  18076. if ( this.aRotation !== 0 ) {
  18077. var cos = Math.cos( this.aRotation );
  18078. var sin = Math.sin( this.aRotation );
  18079. var tx = x - this.aX;
  18080. var ty = y - this.aY;
  18081. // Rotate the point about the center of the ellipse.
  18082. x = tx * cos - ty * sin + this.aX;
  18083. y = tx * sin + ty * cos + this.aY;
  18084. }
  18085. return new Vector2( x, y );
  18086. };
  18087. /**
  18088. * @author zz85 / http://www.lab4games.net/zz85/blog
  18089. */
  18090. exports.CurveUtils = {
  18091. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  18092. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  18093. },
  18094. // Puay Bing, thanks for helping with this derivative!
  18095. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  18096. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  18097. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  18098. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  18099. 3 * t * t * p3;
  18100. },
  18101. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  18102. // To check if my formulas are correct
  18103. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  18104. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  18105. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  18106. var h11 = 3 * t * t - 2 * t; // t3 − t2
  18107. return h00 + h10 + h01 + h11;
  18108. },
  18109. // Catmull-Rom
  18110. interpolate: function( p0, p1, p2, p3, t ) {
  18111. var v0 = ( p2 - p0 ) * 0.5;
  18112. var v1 = ( p3 - p1 ) * 0.5;
  18113. var t2 = t * t;
  18114. var t3 = t * t2;
  18115. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18116. }
  18117. };
  18118. /**************************************************************
  18119. * Spline curve
  18120. **************************************************************/
  18121. function SplineCurve( points /* array of Vector2 */ ) {
  18122. this.points = ( points === undefined ) ? [] : points;
  18123. }
  18124. SplineCurve.prototype = Object.create( Curve.prototype );
  18125. SplineCurve.prototype.constructor = SplineCurve;
  18126. SplineCurve.prototype.isSplineCurve = true;
  18127. SplineCurve.prototype.getPoint = function ( t ) {
  18128. var points = this.points;
  18129. var point = ( points.length - 1 ) * t;
  18130. var intPoint = Math.floor( point );
  18131. var weight = point - intPoint;
  18132. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18133. var point1 = points[ intPoint ];
  18134. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18135. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18136. var interpolate = exports.CurveUtils.interpolate;
  18137. return new Vector2(
  18138. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18139. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  18140. );
  18141. };
  18142. /**************************************************************
  18143. * Cubic Bezier curve
  18144. **************************************************************/
  18145. function CubicBezierCurve( v0, v1, v2, v3 ) {
  18146. this.v0 = v0;
  18147. this.v1 = v1;
  18148. this.v2 = v2;
  18149. this.v3 = v3;
  18150. }
  18151. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  18152. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  18153. CubicBezierCurve.prototype.getPoint = function ( t ) {
  18154. var b3 = exports.ShapeUtils.b3;
  18155. return new Vector2(
  18156. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18157. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18158. );
  18159. };
  18160. CubicBezierCurve.prototype.getTangent = function( t ) {
  18161. var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier;
  18162. return new Vector2(
  18163. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18164. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18165. ).normalize();
  18166. };
  18167. /**************************************************************
  18168. * Quadratic Bezier curve
  18169. **************************************************************/
  18170. function QuadraticBezierCurve( v0, v1, v2 ) {
  18171. this.v0 = v0;
  18172. this.v1 = v1;
  18173. this.v2 = v2;
  18174. }
  18175. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  18176. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  18177. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18178. var b2 = exports.ShapeUtils.b2;
  18179. return new Vector2(
  18180. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  18181. b2( t, this.v0.y, this.v1.y, this.v2.y )
  18182. );
  18183. };
  18184. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18185. var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier;
  18186. return new Vector2(
  18187. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  18188. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  18189. ).normalize();
  18190. };
  18191. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  18192. fromPoints: function ( vectors ) {
  18193. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  18194. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  18195. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  18196. }
  18197. },
  18198. moveTo: function ( x, y ) {
  18199. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  18200. },
  18201. lineTo: function ( x, y ) {
  18202. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  18203. this.curves.push( curve );
  18204. this.currentPoint.set( x, y );
  18205. },
  18206. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  18207. var curve = new QuadraticBezierCurve(
  18208. this.currentPoint.clone(),
  18209. new Vector2( aCPx, aCPy ),
  18210. new Vector2( aX, aY )
  18211. );
  18212. this.curves.push( curve );
  18213. this.currentPoint.set( aX, aY );
  18214. },
  18215. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18216. var curve = new CubicBezierCurve(
  18217. this.currentPoint.clone(),
  18218. new Vector2( aCP1x, aCP1y ),
  18219. new Vector2( aCP2x, aCP2y ),
  18220. new Vector2( aX, aY )
  18221. );
  18222. this.curves.push( curve );
  18223. this.currentPoint.set( aX, aY );
  18224. },
  18225. splineThru: function ( pts /*Array of Vector*/ ) {
  18226. var npts = [ this.currentPoint.clone() ].concat( pts );
  18227. var curve = new SplineCurve( npts );
  18228. this.curves.push( curve );
  18229. this.currentPoint.copy( pts[ pts.length - 1 ] );
  18230. },
  18231. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18232. var x0 = this.currentPoint.x;
  18233. var y0 = this.currentPoint.y;
  18234. this.absarc( aX + x0, aY + y0, aRadius,
  18235. aStartAngle, aEndAngle, aClockwise );
  18236. },
  18237. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18238. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18239. },
  18240. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18241. var x0 = this.currentPoint.x;
  18242. var y0 = this.currentPoint.y;
  18243. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18244. },
  18245. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18246. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18247. if ( this.curves.length > 0 ) {
  18248. // if a previous curve is present, attempt to join
  18249. var firstPoint = curve.getPoint( 0 );
  18250. if ( ! firstPoint.equals( this.currentPoint ) ) {
  18251. this.lineTo( firstPoint.x, firstPoint.y );
  18252. }
  18253. }
  18254. this.curves.push( curve );
  18255. var lastPoint = curve.getPoint( 1 );
  18256. this.currentPoint.copy( lastPoint );
  18257. }
  18258. } );
  18259. /**
  18260. * @author WestLangley / https://github.com/WestLangley
  18261. * @author zz85 / https://github.com/zz85
  18262. * @author miningold / https://github.com/miningold
  18263. * @author jonobr1 / https://github.com/jonobr1
  18264. *
  18265. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18266. *
  18267. * Creates a tube which extrudes along a 3d spline
  18268. *
  18269. * Uses parallel transport frames as described in
  18270. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18271. */
  18272. function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) {
  18273. Geometry.call( this );
  18274. this.type = 'TubeGeometry';
  18275. this.parameters = {
  18276. path: path,
  18277. segments: segments,
  18278. radius: radius,
  18279. radialSegments: radialSegments,
  18280. closed: closed,
  18281. taper: taper
  18282. };
  18283. segments = segments || 64;
  18284. radius = radius || 1;
  18285. radialSegments = radialSegments || 8;
  18286. closed = closed || false;
  18287. taper = taper || TubeGeometry.NoTaper;
  18288. var grid = [];
  18289. var scope = this,
  18290. tangent,
  18291. normal,
  18292. binormal,
  18293. numpoints = segments + 1,
  18294. u, v, r,
  18295. cx, cy,
  18296. pos, pos2 = new Vector3(),
  18297. i, j,
  18298. ip, jp,
  18299. a, b, c, d,
  18300. uva, uvb, uvc, uvd;
  18301. var frames = new TubeGeometry.FrenetFrames( path, segments, closed ),
  18302. tangents = frames.tangents,
  18303. normals = frames.normals,
  18304. binormals = frames.binormals;
  18305. // proxy internals
  18306. this.tangents = tangents;
  18307. this.normals = normals;
  18308. this.binormals = binormals;
  18309. function vert( x, y, z ) {
  18310. return scope.vertices.push( new Vector3( x, y, z ) ) - 1;
  18311. }
  18312. // construct the grid
  18313. for ( i = 0; i < numpoints; i ++ ) {
  18314. grid[ i ] = [];
  18315. u = i / ( numpoints - 1 );
  18316. pos = path.getPointAt( u );
  18317. tangent = tangents[ i ];
  18318. normal = normals[ i ];
  18319. binormal = binormals[ i ];
  18320. r = radius * taper( u );
  18321. for ( j = 0; j < radialSegments; j ++ ) {
  18322. v = j / radialSegments * 2 * Math.PI;
  18323. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18324. cy = r * Math.sin( v );
  18325. pos2.copy( pos );
  18326. pos2.x += cx * normal.x + cy * binormal.x;
  18327. pos2.y += cx * normal.y + cy * binormal.y;
  18328. pos2.z += cx * normal.z + cy * binormal.z;
  18329. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18330. }
  18331. }
  18332. // construct the mesh
  18333. for ( i = 0; i < segments; i ++ ) {
  18334. for ( j = 0; j < radialSegments; j ++ ) {
  18335. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  18336. jp = ( j + 1 ) % radialSegments;
  18337. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18338. b = grid[ ip ][ j ];
  18339. c = grid[ ip ][ jp ];
  18340. d = grid[ i ][ jp ];
  18341. uva = new Vector2( i / segments, j / radialSegments );
  18342. uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments );
  18343. uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  18344. uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments );
  18345. this.faces.push( new Face3( a, b, d ) );
  18346. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18347. this.faces.push( new Face3( b, c, d ) );
  18348. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18349. }
  18350. }
  18351. this.computeFaceNormals();
  18352. this.computeVertexNormals();
  18353. }
  18354. TubeGeometry.prototype = Object.create( Geometry.prototype );
  18355. TubeGeometry.prototype.constructor = TubeGeometry;
  18356. TubeGeometry.NoTaper = function ( u ) {
  18357. return 1;
  18358. };
  18359. TubeGeometry.SinusoidalTaper = function ( u ) {
  18360. return Math.sin( Math.PI * u );
  18361. };
  18362. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18363. TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  18364. var normal = new Vector3(),
  18365. tangents = [],
  18366. normals = [],
  18367. binormals = [],
  18368. vec = new Vector3(),
  18369. mat = new Matrix4(),
  18370. numpoints = segments + 1,
  18371. theta,
  18372. smallest,
  18373. tx, ty, tz,
  18374. i, u;
  18375. // expose internals
  18376. this.tangents = tangents;
  18377. this.normals = normals;
  18378. this.binormals = binormals;
  18379. // compute the tangent vectors for each segment on the path
  18380. for ( i = 0; i < numpoints; i ++ ) {
  18381. u = i / ( numpoints - 1 );
  18382. tangents[ i ] = path.getTangentAt( u );
  18383. tangents[ i ].normalize();
  18384. }
  18385. initialNormal3();
  18386. /*
  18387. function initialNormal1(lastBinormal) {
  18388. // fixed start binormal. Has dangers of 0 vectors
  18389. normals[ 0 ] = new THREE.Vector3();
  18390. binormals[ 0 ] = new THREE.Vector3();
  18391. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18392. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  18393. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18394. }
  18395. function initialNormal2() {
  18396. // This uses the Frenet-Serret formula for deriving binormal
  18397. var t2 = path.getTangentAt( epsilon );
  18398. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  18399. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  18400. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18401. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18402. }
  18403. */
  18404. function initialNormal3() {
  18405. // select an initial normal vector perpendicular to the first tangent vector,
  18406. // and in the direction of the smallest tangent xyz component
  18407. normals[ 0 ] = new Vector3();
  18408. binormals[ 0 ] = new Vector3();
  18409. smallest = Number.MAX_VALUE;
  18410. tx = Math.abs( tangents[ 0 ].x );
  18411. ty = Math.abs( tangents[ 0 ].y );
  18412. tz = Math.abs( tangents[ 0 ].z );
  18413. if ( tx <= smallest ) {
  18414. smallest = tx;
  18415. normal.set( 1, 0, 0 );
  18416. }
  18417. if ( ty <= smallest ) {
  18418. smallest = ty;
  18419. normal.set( 0, 1, 0 );
  18420. }
  18421. if ( tz <= smallest ) {
  18422. normal.set( 0, 0, 1 );
  18423. }
  18424. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18425. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18426. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18427. }
  18428. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18429. for ( i = 1; i < numpoints; i ++ ) {
  18430. normals[ i ] = normals[ i - 1 ].clone();
  18431. binormals[ i ] = binormals[ i - 1 ].clone();
  18432. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18433. if ( vec.length() > Number.EPSILON ) {
  18434. vec.normalize();
  18435. theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18436. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18437. }
  18438. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18439. }
  18440. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18441. if ( closed ) {
  18442. theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  18443. theta /= ( numpoints - 1 );
  18444. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  18445. theta = - theta;
  18446. }
  18447. for ( i = 1; i < numpoints; i ++ ) {
  18448. // twist a little...
  18449. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18450. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18451. }
  18452. }
  18453. };
  18454. /**
  18455. * @author zz85 / http://www.lab4games.net/zz85/blog
  18456. *
  18457. * Creates extruded geometry from a path shape.
  18458. *
  18459. * parameters = {
  18460. *
  18461. * curveSegments: <int>, // number of points on the curves
  18462. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18463. * amount: <int>, // Depth to extrude the shape
  18464. *
  18465. * bevelEnabled: <bool>, // turn on bevel
  18466. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18467. * bevelSize: <float>, // how far from shape outline is bevel
  18468. * bevelSegments: <int>, // number of bevel layers
  18469. *
  18470. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18471. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18472. *
  18473. * uvGenerator: <Object> // object that provides UV generator functions
  18474. *
  18475. * }
  18476. **/
  18477. function ExtrudeGeometry( shapes, options ) {
  18478. if ( typeof( shapes ) === "undefined" ) {
  18479. shapes = [];
  18480. return;
  18481. }
  18482. Geometry.call( this );
  18483. this.type = 'ExtrudeGeometry';
  18484. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18485. this.addShapeList( shapes, options );
  18486. this.computeFaceNormals();
  18487. // can't really use automatic vertex normals
  18488. // as then front and back sides get smoothed too
  18489. // should do separate smoothing just for sides
  18490. //this.computeVertexNormals();
  18491. //console.log( "took", ( Date.now() - startTime ) );
  18492. }
  18493. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  18494. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18495. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18496. var sl = shapes.length;
  18497. for ( var s = 0; s < sl; s ++ ) {
  18498. var shape = shapes[ s ];
  18499. this.addShape( shape, options );
  18500. }
  18501. };
  18502. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18503. var amount = options.amount !== undefined ? options.amount : 100;
  18504. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18505. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18506. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18507. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18508. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18509. var steps = options.steps !== undefined ? options.steps : 1;
  18510. var extrudePath = options.extrudePath;
  18511. var extrudePts, extrudeByPath = false;
  18512. // Use default WorldUVGenerator if no UV generators are specified.
  18513. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  18514. var splineTube, binormal, normal, position2;
  18515. if ( extrudePath ) {
  18516. extrudePts = extrudePath.getSpacedPoints( steps );
  18517. extrudeByPath = true;
  18518. bevelEnabled = false; // bevels not supported for path extrusion
  18519. // SETUP TNB variables
  18520. // Reuse TNB from TubeGeomtry for now.
  18521. // TODO1 - have a .isClosed in spline?
  18522. splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false );
  18523. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18524. binormal = new Vector3();
  18525. normal = new Vector3();
  18526. position2 = new Vector3();
  18527. }
  18528. // Safeguards if bevels are not enabled
  18529. if ( ! bevelEnabled ) {
  18530. bevelSegments = 0;
  18531. bevelThickness = 0;
  18532. bevelSize = 0;
  18533. }
  18534. // Variables initialization
  18535. var ahole, h, hl; // looping of holes
  18536. var scope = this;
  18537. var shapesOffset = this.vertices.length;
  18538. var shapePoints = shape.extractPoints( curveSegments );
  18539. var vertices = shapePoints.shape;
  18540. var holes = shapePoints.holes;
  18541. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18542. if ( reverse ) {
  18543. vertices = vertices.reverse();
  18544. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18545. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18546. ahole = holes[ h ];
  18547. if ( exports.ShapeUtils.isClockWise( ahole ) ) {
  18548. holes[ h ] = ahole.reverse();
  18549. }
  18550. }
  18551. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18552. }
  18553. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18554. /* Vertices */
  18555. var contour = vertices; // vertices has all points but contour has only points of circumference
  18556. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18557. ahole = holes[ h ];
  18558. vertices = vertices.concat( ahole );
  18559. }
  18560. function scalePt2( pt, vec, size ) {
  18561. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18562. return vec.clone().multiplyScalar( size ).add( pt );
  18563. }
  18564. var b, bs, t, z,
  18565. vert, vlen = vertices.length,
  18566. face, flen = faces.length;
  18567. // Find directions for point movement
  18568. function getBevelVec( inPt, inPrev, inNext ) {
  18569. // computes for inPt the corresponding point inPt' on a new contour
  18570. // shifted by 1 unit (length of normalized vector) to the left
  18571. // if we walk along contour clockwise, this new contour is outside the old one
  18572. //
  18573. // inPt' is the intersection of the two lines parallel to the two
  18574. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18575. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18576. // good reading for geometry algorithms (here: line-line intersection)
  18577. // http://geomalgorithms.com/a05-_intersect-1.html
  18578. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18579. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18580. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18581. // check for collinear edges
  18582. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18583. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18584. // not collinear
  18585. // length of vectors for normalizing
  18586. var v_prev_len = Math.sqrt( v_prev_lensq );
  18587. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18588. // shift adjacent points by unit vectors to the left
  18589. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18590. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18591. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18592. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18593. // scaling factor for v_prev to intersection point
  18594. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18595. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18596. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18597. // vector from inPt to intersection point
  18598. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18599. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18600. // Don't normalize!, otherwise sharp corners become ugly
  18601. // but prevent crazy spikes
  18602. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18603. if ( v_trans_lensq <= 2 ) {
  18604. return new Vector2( v_trans_x, v_trans_y );
  18605. } else {
  18606. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18607. }
  18608. } else {
  18609. // handle special case of collinear edges
  18610. var direction_eq = false; // assumes: opposite
  18611. if ( v_prev_x > Number.EPSILON ) {
  18612. if ( v_next_x > Number.EPSILON ) {
  18613. direction_eq = true;
  18614. }
  18615. } else {
  18616. if ( v_prev_x < - Number.EPSILON ) {
  18617. if ( v_next_x < - Number.EPSILON ) {
  18618. direction_eq = true;
  18619. }
  18620. } else {
  18621. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18622. direction_eq = true;
  18623. }
  18624. }
  18625. }
  18626. if ( direction_eq ) {
  18627. // console.log("Warning: lines are a straight sequence");
  18628. v_trans_x = - v_prev_y;
  18629. v_trans_y = v_prev_x;
  18630. shrink_by = Math.sqrt( v_prev_lensq );
  18631. } else {
  18632. // console.log("Warning: lines are a straight spike");
  18633. v_trans_x = v_prev_x;
  18634. v_trans_y = v_prev_y;
  18635. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18636. }
  18637. }
  18638. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18639. }
  18640. var contourMovements = [];
  18641. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18642. if ( j === il ) j = 0;
  18643. if ( k === il ) k = 0;
  18644. // (j)---(i)---(k)
  18645. // console.log('i,j,k', i, j , k)
  18646. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18647. }
  18648. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18649. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18650. ahole = holes[ h ];
  18651. oneHoleMovements = [];
  18652. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18653. if ( j === il ) j = 0;
  18654. if ( k === il ) k = 0;
  18655. // (j)---(i)---(k)
  18656. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18657. }
  18658. holesMovements.push( oneHoleMovements );
  18659. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18660. }
  18661. // Loop bevelSegments, 1 for the front, 1 for the back
  18662. for ( b = 0; b < bevelSegments; b ++ ) {
  18663. //for ( b = bevelSegments; b > 0; b -- ) {
  18664. t = b / bevelSegments;
  18665. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18666. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18667. // contract shape
  18668. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18669. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18670. v( vert.x, vert.y, - z );
  18671. }
  18672. // expand holes
  18673. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18674. ahole = holes[ h ];
  18675. oneHoleMovements = holesMovements[ h ];
  18676. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18677. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18678. v( vert.x, vert.y, - z );
  18679. }
  18680. }
  18681. }
  18682. bs = bevelSize;
  18683. // Back facing vertices
  18684. for ( i = 0; i < vlen; i ++ ) {
  18685. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18686. if ( ! extrudeByPath ) {
  18687. v( vert.x, vert.y, 0 );
  18688. } else {
  18689. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18690. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18691. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18692. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18693. v( position2.x, position2.y, position2.z );
  18694. }
  18695. }
  18696. // Add stepped vertices...
  18697. // Including front facing vertices
  18698. var s;
  18699. for ( s = 1; s <= steps; s ++ ) {
  18700. for ( i = 0; i < vlen; i ++ ) {
  18701. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18702. if ( ! extrudeByPath ) {
  18703. v( vert.x, vert.y, amount / steps * s );
  18704. } else {
  18705. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18706. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18707. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18708. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18709. v( position2.x, position2.y, position2.z );
  18710. }
  18711. }
  18712. }
  18713. // Add bevel segments planes
  18714. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18715. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18716. t = b / bevelSegments;
  18717. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  18718. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18719. // contract shape
  18720. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18721. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18722. v( vert.x, vert.y, amount + z );
  18723. }
  18724. // expand holes
  18725. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18726. ahole = holes[ h ];
  18727. oneHoleMovements = holesMovements[ h ];
  18728. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18729. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18730. if ( ! extrudeByPath ) {
  18731. v( vert.x, vert.y, amount + z );
  18732. } else {
  18733. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18734. }
  18735. }
  18736. }
  18737. }
  18738. /* Faces */
  18739. // Top and bottom faces
  18740. buildLidFaces();
  18741. // Sides faces
  18742. buildSideFaces();
  18743. ///// Internal functions
  18744. function buildLidFaces() {
  18745. if ( bevelEnabled ) {
  18746. var layer = 0; // steps + 1
  18747. var offset = vlen * layer;
  18748. // Bottom faces
  18749. for ( i = 0; i < flen; i ++ ) {
  18750. face = faces[ i ];
  18751. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18752. }
  18753. layer = steps + bevelSegments * 2;
  18754. offset = vlen * layer;
  18755. // Top faces
  18756. for ( i = 0; i < flen; i ++ ) {
  18757. face = faces[ i ];
  18758. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18759. }
  18760. } else {
  18761. // Bottom faces
  18762. for ( i = 0; i < flen; i ++ ) {
  18763. face = faces[ i ];
  18764. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18765. }
  18766. // Top faces
  18767. for ( i = 0; i < flen; i ++ ) {
  18768. face = faces[ i ];
  18769. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18770. }
  18771. }
  18772. }
  18773. // Create faces for the z-sides of the shape
  18774. function buildSideFaces() {
  18775. var layeroffset = 0;
  18776. sidewalls( contour, layeroffset );
  18777. layeroffset += contour.length;
  18778. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18779. ahole = holes[ h ];
  18780. sidewalls( ahole, layeroffset );
  18781. //, true
  18782. layeroffset += ahole.length;
  18783. }
  18784. }
  18785. function sidewalls( contour, layeroffset ) {
  18786. var j, k;
  18787. i = contour.length;
  18788. while ( -- i >= 0 ) {
  18789. j = i;
  18790. k = i - 1;
  18791. if ( k < 0 ) k = contour.length - 1;
  18792. //console.log('b', i,j, i-1, k,vertices.length);
  18793. var s = 0, sl = steps + bevelSegments * 2;
  18794. for ( s = 0; s < sl; s ++ ) {
  18795. var slen1 = vlen * s;
  18796. var slen2 = vlen * ( s + 1 );
  18797. var a = layeroffset + j + slen1,
  18798. b = layeroffset + k + slen1,
  18799. c = layeroffset + k + slen2,
  18800. d = layeroffset + j + slen2;
  18801. f4( a, b, c, d, contour, s, sl, j, k );
  18802. }
  18803. }
  18804. }
  18805. function v( x, y, z ) {
  18806. scope.vertices.push( new Vector3( x, y, z ) );
  18807. }
  18808. function f3( a, b, c ) {
  18809. a += shapesOffset;
  18810. b += shapesOffset;
  18811. c += shapesOffset;
  18812. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  18813. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18814. scope.faceVertexUvs[ 0 ].push( uvs );
  18815. }
  18816. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18817. a += shapesOffset;
  18818. b += shapesOffset;
  18819. c += shapesOffset;
  18820. d += shapesOffset;
  18821. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  18822. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  18823. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18824. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18825. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18826. }
  18827. };
  18828. ExtrudeGeometry.WorldUVGenerator = {
  18829. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18830. var vertices = geometry.vertices;
  18831. var a = vertices[ indexA ];
  18832. var b = vertices[ indexB ];
  18833. var c = vertices[ indexC ];
  18834. return [
  18835. new Vector2( a.x, a.y ),
  18836. new Vector2( b.x, b.y ),
  18837. new Vector2( c.x, c.y )
  18838. ];
  18839. },
  18840. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18841. var vertices = geometry.vertices;
  18842. var a = vertices[ indexA ];
  18843. var b = vertices[ indexB ];
  18844. var c = vertices[ indexC ];
  18845. var d = vertices[ indexD ];
  18846. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18847. return [
  18848. new Vector2( a.x, 1 - a.z ),
  18849. new Vector2( b.x, 1 - b.z ),
  18850. new Vector2( c.x, 1 - c.z ),
  18851. new Vector2( d.x, 1 - d.z )
  18852. ];
  18853. } else {
  18854. return [
  18855. new Vector2( a.y, 1 - a.z ),
  18856. new Vector2( b.y, 1 - b.z ),
  18857. new Vector2( c.y, 1 - c.z ),
  18858. new Vector2( d.y, 1 - d.z )
  18859. ];
  18860. }
  18861. }
  18862. };
  18863. /**
  18864. * @author jonobr1 / http://jonobr1.com
  18865. *
  18866. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18867. * ExtrudeGeometry.
  18868. *
  18869. * parameters = {
  18870. *
  18871. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18872. *
  18873. * material: <int> // material index for front and back faces
  18874. * uvGenerator: <Object> // object that provides UV generator functions
  18875. *
  18876. * }
  18877. **/
  18878. function ShapeGeometry( shapes, options ) {
  18879. Geometry.call( this );
  18880. this.type = 'ShapeGeometry';
  18881. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  18882. this.addShapeList( shapes, options );
  18883. this.computeFaceNormals();
  18884. }
  18885. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  18886. ShapeGeometry.prototype.constructor = ShapeGeometry;
  18887. /**
  18888. * Add an array of shapes to THREE.ShapeGeometry.
  18889. */
  18890. ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18891. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18892. this.addShape( shapes[ i ], options );
  18893. }
  18894. return this;
  18895. };
  18896. /**
  18897. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18898. */
  18899. ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18900. if ( options === undefined ) options = {};
  18901. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18902. var material = options.material;
  18903. var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18904. //
  18905. var i, l, hole;
  18906. var shapesOffset = this.vertices.length;
  18907. var shapePoints = shape.extractPoints( curveSegments );
  18908. var vertices = shapePoints.shape;
  18909. var holes = shapePoints.holes;
  18910. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18911. if ( reverse ) {
  18912. vertices = vertices.reverse();
  18913. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18914. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18915. hole = holes[ i ];
  18916. if ( exports.ShapeUtils.isClockWise( hole ) ) {
  18917. holes[ i ] = hole.reverse();
  18918. }
  18919. }
  18920. reverse = false;
  18921. }
  18922. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18923. // Vertices
  18924. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18925. hole = holes[ i ];
  18926. vertices = vertices.concat( hole );
  18927. }
  18928. //
  18929. var vert, vlen = vertices.length;
  18930. var face, flen = faces.length;
  18931. for ( i = 0; i < vlen; i ++ ) {
  18932. vert = vertices[ i ];
  18933. this.vertices.push( new Vector3( vert.x, vert.y, 0 ) );
  18934. }
  18935. for ( i = 0; i < flen; i ++ ) {
  18936. face = faces[ i ];
  18937. var a = face[ 0 ] + shapesOffset;
  18938. var b = face[ 1 ] + shapesOffset;
  18939. var c = face[ 2 ] + shapesOffset;
  18940. this.faces.push( new Face3( a, b, c, null, null, material ) );
  18941. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18942. }
  18943. };
  18944. /**
  18945. * @author zz85 / http://www.lab4games.net/zz85/blog
  18946. * Defines a 2d shape plane using paths.
  18947. **/
  18948. // STEP 1 Create a path.
  18949. // STEP 2 Turn path into shape.
  18950. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18951. // STEP 3a - Extract points from each shape, turn to vertices
  18952. // STEP 3b - Triangulate each shape, add faces.
  18953. function Shape() {
  18954. Path.apply( this, arguments );
  18955. this.holes = [];
  18956. }
  18957. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  18958. constructor: Shape,
  18959. // Convenience method to return ExtrudeGeometry
  18960. extrude: function ( options ) {
  18961. return new ExtrudeGeometry( this, options );
  18962. },
  18963. // Convenience method to return ShapeGeometry
  18964. makeGeometry: function ( options ) {
  18965. return new ShapeGeometry( this, options );
  18966. },
  18967. getPointsHoles: function ( divisions ) {
  18968. var holesPts = [];
  18969. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  18970. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18971. }
  18972. return holesPts;
  18973. },
  18974. // Get points of shape and holes (keypoints based on segments parameter)
  18975. extractAllPoints: function ( divisions ) {
  18976. return {
  18977. shape: this.getPoints( divisions ),
  18978. holes: this.getPointsHoles( divisions )
  18979. };
  18980. },
  18981. extractPoints: function ( divisions ) {
  18982. return this.extractAllPoints( divisions );
  18983. }
  18984. } );
  18985. /**
  18986. * @author zz85 / http://www.lab4games.net/zz85/blog
  18987. * Creates free form 2d path using series of points, lines or curves.
  18988. *
  18989. **/
  18990. function Path( points ) {
  18991. CurvePath.call( this );
  18992. this.currentPoint = new Vector2();
  18993. if ( points ) {
  18994. this.fromPoints( points );
  18995. }
  18996. }
  18997. Path.prototype = PathPrototype;
  18998. PathPrototype.constructor = Path;
  18999. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  19000. function ShapePath() {
  19001. this.subPaths = [];
  19002. this.currentPath = null;
  19003. }
  19004. ShapePath.prototype = {
  19005. moveTo: function ( x, y ) {
  19006. this.currentPath = new Path();
  19007. this.subPaths.push(this.currentPath);
  19008. this.currentPath.moveTo( x, y );
  19009. },
  19010. lineTo: function ( x, y ) {
  19011. this.currentPath.lineTo( x, y );
  19012. },
  19013. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  19014. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  19015. },
  19016. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19017. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  19018. },
  19019. splineThru: function ( pts ) {
  19020. this.currentPath.splineThru( pts );
  19021. },
  19022. toShapes: function ( isCCW, noHoles ) {
  19023. function toShapesNoHoles( inSubpaths ) {
  19024. var shapes = [];
  19025. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  19026. var tmpPath = inSubpaths[ i ];
  19027. var tmpShape = new Shape();
  19028. tmpShape.curves = tmpPath.curves;
  19029. shapes.push( tmpShape );
  19030. }
  19031. return shapes;
  19032. }
  19033. function isPointInsidePolygon( inPt, inPolygon ) {
  19034. var polyLen = inPolygon.length;
  19035. // inPt on polygon contour => immediate success or
  19036. // toggling of inside/outside at every single! intersection point of an edge
  19037. // with the horizontal line through inPt, left of inPt
  19038. // not counting lowerY endpoints of edges and whole edges on that line
  19039. var inside = false;
  19040. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  19041. var edgeLowPt = inPolygon[ p ];
  19042. var edgeHighPt = inPolygon[ q ];
  19043. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  19044. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  19045. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  19046. // not parallel
  19047. if ( edgeDy < 0 ) {
  19048. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  19049. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  19050. }
  19051. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  19052. if ( inPt.y === edgeLowPt.y ) {
  19053. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  19054. // continue; // no intersection or edgeLowPt => doesn't count !!!
  19055. } else {
  19056. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  19057. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  19058. if ( perpEdge < 0 ) continue;
  19059. inside = ! inside; // true intersection left of inPt
  19060. }
  19061. } else {
  19062. // parallel or collinear
  19063. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  19064. // edge lies on the same horizontal line as inPt
  19065. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  19066. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  19067. // continue;
  19068. }
  19069. }
  19070. return inside;
  19071. }
  19072. var isClockWise = exports.ShapeUtils.isClockWise;
  19073. var subPaths = this.subPaths;
  19074. if ( subPaths.length === 0 ) return [];
  19075. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  19076. var solid, tmpPath, tmpShape, shapes = [];
  19077. if ( subPaths.length === 1 ) {
  19078. tmpPath = subPaths[ 0 ];
  19079. tmpShape = new Shape();
  19080. tmpShape.curves = tmpPath.curves;
  19081. shapes.push( tmpShape );
  19082. return shapes;
  19083. }
  19084. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  19085. holesFirst = isCCW ? ! holesFirst : holesFirst;
  19086. // console.log("Holes first", holesFirst);
  19087. var betterShapeHoles = [];
  19088. var newShapes = [];
  19089. var newShapeHoles = [];
  19090. var mainIdx = 0;
  19091. var tmpPoints;
  19092. newShapes[ mainIdx ] = undefined;
  19093. newShapeHoles[ mainIdx ] = [];
  19094. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  19095. tmpPath = subPaths[ i ];
  19096. tmpPoints = tmpPath.getPoints();
  19097. solid = isClockWise( tmpPoints );
  19098. solid = isCCW ? ! solid : solid;
  19099. if ( solid ) {
  19100. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  19101. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  19102. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  19103. if ( holesFirst ) mainIdx ++;
  19104. newShapeHoles[ mainIdx ] = [];
  19105. //console.log('cw', i);
  19106. } else {
  19107. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  19108. //console.log('ccw', i);
  19109. }
  19110. }
  19111. // only Holes? -> probably all Shapes with wrong orientation
  19112. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  19113. if ( newShapes.length > 1 ) {
  19114. var ambiguous = false;
  19115. var toChange = [];
  19116. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19117. betterShapeHoles[ sIdx ] = [];
  19118. }
  19119. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19120. var sho = newShapeHoles[ sIdx ];
  19121. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  19122. var ho = sho[ hIdx ];
  19123. var hole_unassigned = true;
  19124. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  19125. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  19126. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  19127. if ( hole_unassigned ) {
  19128. hole_unassigned = false;
  19129. betterShapeHoles[ s2Idx ].push( ho );
  19130. } else {
  19131. ambiguous = true;
  19132. }
  19133. }
  19134. }
  19135. if ( hole_unassigned ) {
  19136. betterShapeHoles[ sIdx ].push( ho );
  19137. }
  19138. }
  19139. }
  19140. // console.log("ambiguous: ", ambiguous);
  19141. if ( toChange.length > 0 ) {
  19142. // console.log("to change: ", toChange);
  19143. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  19144. }
  19145. }
  19146. var tmpHoles;
  19147. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  19148. tmpShape = newShapes[ i ].s;
  19149. shapes.push( tmpShape );
  19150. tmpHoles = newShapeHoles[ i ];
  19151. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  19152. tmpShape.holes.push( tmpHoles[ j ].h );
  19153. }
  19154. }
  19155. //console.log("shape", shapes);
  19156. return shapes;
  19157. }
  19158. }
  19159. /**
  19160. * @author zz85 / http://www.lab4games.net/zz85/blog
  19161. * @author mrdoob / http://mrdoob.com/
  19162. */
  19163. function Font( data ) {
  19164. this.data = data;
  19165. }
  19166. Object.assign( Font.prototype, {
  19167. isFont: true,
  19168. generateShapes: function ( text, size, divisions ) {
  19169. function createPaths( text ) {
  19170. var chars = String( text ).split( '' );
  19171. var scale = size / data.resolution;
  19172. var offset = 0;
  19173. var paths = [];
  19174. for ( var i = 0; i < chars.length; i ++ ) {
  19175. var ret = createPath( chars[ i ], scale, offset );
  19176. offset += ret.offset;
  19177. paths.push( ret.path );
  19178. }
  19179. return paths;
  19180. }
  19181. function createPath( c, scale, offset ) {
  19182. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  19183. if ( ! glyph ) return;
  19184. var path = new ShapePath();
  19185. var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3;
  19186. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  19187. if ( glyph.o ) {
  19188. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  19189. for ( var i = 0, l = outline.length; i < l; ) {
  19190. var action = outline[ i ++ ];
  19191. switch ( action ) {
  19192. case 'm': // moveTo
  19193. x = outline[ i ++ ] * scale + offset;
  19194. y = outline[ i ++ ] * scale;
  19195. path.moveTo( x, y );
  19196. break;
  19197. case 'l': // lineTo
  19198. x = outline[ i ++ ] * scale + offset;
  19199. y = outline[ i ++ ] * scale;
  19200. path.lineTo( x, y );
  19201. break;
  19202. case 'q': // quadraticCurveTo
  19203. cpx = outline[ i ++ ] * scale + offset;
  19204. cpy = outline[ i ++ ] * scale;
  19205. cpx1 = outline[ i ++ ] * scale + offset;
  19206. cpy1 = outline[ i ++ ] * scale;
  19207. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  19208. laste = pts[ pts.length - 1 ];
  19209. if ( laste ) {
  19210. cpx0 = laste.x;
  19211. cpy0 = laste.y;
  19212. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19213. var t = i2 / divisions;
  19214. b2( t, cpx0, cpx1, cpx );
  19215. b2( t, cpy0, cpy1, cpy );
  19216. }
  19217. }
  19218. break;
  19219. case 'b': // bezierCurveTo
  19220. cpx = outline[ i ++ ] * scale + offset;
  19221. cpy = outline[ i ++ ] * scale;
  19222. cpx1 = outline[ i ++ ] * scale + offset;
  19223. cpy1 = outline[ i ++ ] * scale;
  19224. cpx2 = outline[ i ++ ] * scale + offset;
  19225. cpy2 = outline[ i ++ ] * scale;
  19226. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  19227. laste = pts[ pts.length - 1 ];
  19228. if ( laste ) {
  19229. cpx0 = laste.x;
  19230. cpy0 = laste.y;
  19231. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19232. var t = i2 / divisions;
  19233. b3( t, cpx0, cpx1, cpx2, cpx );
  19234. b3( t, cpy0, cpy1, cpy2, cpy );
  19235. }
  19236. }
  19237. break;
  19238. }
  19239. }
  19240. }
  19241. return { offset: glyph.ha * scale, path: path };
  19242. }
  19243. //
  19244. if ( size === undefined ) size = 100;
  19245. if ( divisions === undefined ) divisions = 4;
  19246. var data = this.data;
  19247. var paths = createPaths( text );
  19248. var shapes = [];
  19249. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  19250. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  19251. }
  19252. return shapes;
  19253. }
  19254. } );
  19255. /**
  19256. * @author mrdoob / http://mrdoob.com/
  19257. */
  19258. function FontLoader( manager ) {
  19259. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19260. }
  19261. Object.assign( FontLoader.prototype, {
  19262. load: function ( url, onLoad, onProgress, onError ) {
  19263. var scope = this;
  19264. var loader = new XHRLoader( this.manager );
  19265. loader.load( url, function ( text ) {
  19266. var json;
  19267. try {
  19268. json = JSON.parse( text );
  19269. } catch ( e ) {
  19270. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  19271. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  19272. }
  19273. var font = scope.parse( json );
  19274. if ( onLoad ) onLoad( font );
  19275. }, onProgress, onError );
  19276. },
  19277. parse: function ( json ) {
  19278. return new Font( json );
  19279. }
  19280. } );
  19281. var context;
  19282. function getAudioContext() {
  19283. if ( context === undefined ) {
  19284. context = new ( window.AudioContext || window.webkitAudioContext )();
  19285. }
  19286. return context;
  19287. }
  19288. /**
  19289. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  19290. */
  19291. function AudioLoader( manager ) {
  19292. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19293. }
  19294. Object.assign( AudioLoader.prototype, {
  19295. load: function ( url, onLoad, onProgress, onError ) {
  19296. var loader = new XHRLoader( this.manager );
  19297. loader.setResponseType( 'arraybuffer' );
  19298. loader.load( url, function ( buffer ) {
  19299. var context = getAudioContext();
  19300. context.decodeAudioData( buffer, function ( audioBuffer ) {
  19301. onLoad( audioBuffer );
  19302. } );
  19303. }, onProgress, onError );
  19304. }
  19305. } );
  19306. /**
  19307. * @author mrdoob / http://mrdoob.com/
  19308. */
  19309. function StereoCamera() {
  19310. this.type = 'StereoCamera';
  19311. this.aspect = 1;
  19312. this.eyeSep = 0.064;
  19313. this.cameraL = new PerspectiveCamera();
  19314. this.cameraL.layers.enable( 1 );
  19315. this.cameraL.matrixAutoUpdate = false;
  19316. this.cameraR = new PerspectiveCamera();
  19317. this.cameraR.layers.enable( 2 );
  19318. this.cameraR.matrixAutoUpdate = false;
  19319. }
  19320. Object.assign( StereoCamera.prototype, {
  19321. update: ( function () {
  19322. var focus, fov, aspect, near, far;
  19323. var eyeRight = new Matrix4();
  19324. var eyeLeft = new Matrix4();
  19325. return function update( camera ) {
  19326. var needsUpdate = focus !== camera.focus || fov !== camera.fov ||
  19327. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  19328. far !== camera.far;
  19329. if ( needsUpdate ) {
  19330. focus = camera.focus;
  19331. fov = camera.fov;
  19332. aspect = camera.aspect * this.aspect;
  19333. near = camera.near;
  19334. far = camera.far;
  19335. // Off-axis stereoscopic effect based on
  19336. // http://paulbourke.net/stereographics/stereorender/
  19337. var projectionMatrix = camera.projectionMatrix.clone();
  19338. var eyeSep = this.eyeSep / 2;
  19339. var eyeSepOnProjection = eyeSep * near / focus;
  19340. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  19341. var xmin, xmax;
  19342. // translate xOffset
  19343. eyeLeft.elements[ 12 ] = - eyeSep;
  19344. eyeRight.elements[ 12 ] = eyeSep;
  19345. // for left eye
  19346. xmin = - ymax * aspect + eyeSepOnProjection;
  19347. xmax = ymax * aspect + eyeSepOnProjection;
  19348. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19349. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19350. this.cameraL.projectionMatrix.copy( projectionMatrix );
  19351. // for right eye
  19352. xmin = - ymax * aspect - eyeSepOnProjection;
  19353. xmax = ymax * aspect - eyeSepOnProjection;
  19354. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19355. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19356. this.cameraR.projectionMatrix.copy( projectionMatrix );
  19357. }
  19358. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  19359. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  19360. };
  19361. } )()
  19362. } );
  19363. /**
  19364. * Camera for rendering cube maps
  19365. * - renders scene into axis-aligned cube
  19366. *
  19367. * @author alteredq / http://alteredqualia.com/
  19368. */
  19369. function CubeCamera( near, far, cubeResolution ) {
  19370. Object3D.call( this );
  19371. this.type = 'CubeCamera';
  19372. var fov = 90, aspect = 1;
  19373. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  19374. cameraPX.up.set( 0, - 1, 0 );
  19375. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  19376. this.add( cameraPX );
  19377. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  19378. cameraNX.up.set( 0, - 1, 0 );
  19379. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  19380. this.add( cameraNX );
  19381. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  19382. cameraPY.up.set( 0, 0, 1 );
  19383. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  19384. this.add( cameraPY );
  19385. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  19386. cameraNY.up.set( 0, 0, - 1 );
  19387. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  19388. this.add( cameraNY );
  19389. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  19390. cameraPZ.up.set( 0, - 1, 0 );
  19391. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  19392. this.add( cameraPZ );
  19393. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  19394. cameraNZ.up.set( 0, - 1, 0 );
  19395. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  19396. this.add( cameraNZ );
  19397. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  19398. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  19399. this.updateCubeMap = function ( renderer, scene ) {
  19400. if ( this.parent === null ) this.updateMatrixWorld();
  19401. var renderTarget = this.renderTarget;
  19402. var generateMipmaps = renderTarget.texture.generateMipmaps;
  19403. renderTarget.texture.generateMipmaps = false;
  19404. renderTarget.activeCubeFace = 0;
  19405. renderer.render( scene, cameraPX, renderTarget );
  19406. renderTarget.activeCubeFace = 1;
  19407. renderer.render( scene, cameraNX, renderTarget );
  19408. renderTarget.activeCubeFace = 2;
  19409. renderer.render( scene, cameraPY, renderTarget );
  19410. renderTarget.activeCubeFace = 3;
  19411. renderer.render( scene, cameraNY, renderTarget );
  19412. renderTarget.activeCubeFace = 4;
  19413. renderer.render( scene, cameraPZ, renderTarget );
  19414. renderTarget.texture.generateMipmaps = generateMipmaps;
  19415. renderTarget.activeCubeFace = 5;
  19416. renderer.render( scene, cameraNZ, renderTarget );
  19417. renderer.setRenderTarget( null );
  19418. };
  19419. }
  19420. CubeCamera.prototype = Object.create( Object3D.prototype );
  19421. CubeCamera.prototype.constructor = CubeCamera;
  19422. function AudioListener() {
  19423. Object3D.call( this );
  19424. this.type = 'AudioListener';
  19425. this.context = getAudioContext();
  19426. this.gain = this.context.createGain();
  19427. this.gain.connect( this.context.destination );
  19428. this.filter = null;
  19429. }
  19430. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19431. constructor: AudioListener,
  19432. getInput: function () {
  19433. return this.gain;
  19434. },
  19435. removeFilter: function ( ) {
  19436. if ( this.filter !== null ) {
  19437. this.gain.disconnect( this.filter );
  19438. this.filter.disconnect( this.context.destination );
  19439. this.gain.connect( this.context.destination );
  19440. this.filter = null;
  19441. }
  19442. },
  19443. getFilter: function () {
  19444. return this.filter;
  19445. },
  19446. setFilter: function ( value ) {
  19447. if ( this.filter !== null ) {
  19448. this.gain.disconnect( this.filter );
  19449. this.filter.disconnect( this.context.destination );
  19450. } else {
  19451. this.gain.disconnect( this.context.destination );
  19452. }
  19453. this.filter = value;
  19454. this.gain.connect( this.filter );
  19455. this.filter.connect( this.context.destination );
  19456. },
  19457. getMasterVolume: function () {
  19458. return this.gain.gain.value;
  19459. },
  19460. setMasterVolume: function ( value ) {
  19461. this.gain.gain.value = value;
  19462. },
  19463. updateMatrixWorld: ( function () {
  19464. var position = new Vector3();
  19465. var quaternion = new Quaternion();
  19466. var scale = new Vector3();
  19467. var orientation = new Vector3();
  19468. return function updateMatrixWorld( force ) {
  19469. Object3D.prototype.updateMatrixWorld.call( this, force );
  19470. var listener = this.context.listener;
  19471. var up = this.up;
  19472. this.matrixWorld.decompose( position, quaternion, scale );
  19473. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  19474. listener.setPosition( position.x, position.y, position.z );
  19475. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  19476. };
  19477. } )()
  19478. } );
  19479. function Audio( listener ) {
  19480. Object3D.call( this );
  19481. this.type = 'Audio';
  19482. this.context = listener.context;
  19483. this.source = this.context.createBufferSource();
  19484. this.source.onended = this.onEnded.bind( this );
  19485. this.gain = this.context.createGain();
  19486. this.gain.connect( listener.getInput() );
  19487. this.autoplay = false;
  19488. this.startTime = 0;
  19489. this.playbackRate = 1;
  19490. this.isPlaying = false;
  19491. this.hasPlaybackControl = true;
  19492. this.sourceType = 'empty';
  19493. this.filters = [];
  19494. }
  19495. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19496. constructor: Audio,
  19497. getOutput: function () {
  19498. return this.gain;
  19499. },
  19500. setNodeSource: function ( audioNode ) {
  19501. this.hasPlaybackControl = false;
  19502. this.sourceType = 'audioNode';
  19503. this.source = audioNode;
  19504. this.connect();
  19505. return this;
  19506. },
  19507. setBuffer: function ( audioBuffer ) {
  19508. this.source.buffer = audioBuffer;
  19509. this.sourceType = 'buffer';
  19510. if ( this.autoplay ) this.play();
  19511. return this;
  19512. },
  19513. play: function () {
  19514. if ( this.isPlaying === true ) {
  19515. console.warn( 'THREE.Audio: Audio is already playing.' );
  19516. return;
  19517. }
  19518. if ( this.hasPlaybackControl === false ) {
  19519. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19520. return;
  19521. }
  19522. var source = this.context.createBufferSource();
  19523. source.buffer = this.source.buffer;
  19524. source.loop = this.source.loop;
  19525. source.onended = this.source.onended;
  19526. source.start( 0, this.startTime );
  19527. source.playbackRate.value = this.playbackRate;
  19528. this.isPlaying = true;
  19529. this.source = source;
  19530. return this.connect();
  19531. },
  19532. pause: function () {
  19533. if ( this.hasPlaybackControl === false ) {
  19534. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19535. return;
  19536. }
  19537. this.source.stop();
  19538. this.startTime = this.context.currentTime;
  19539. this.isPlaying = false;
  19540. return this;
  19541. },
  19542. stop: function () {
  19543. if ( this.hasPlaybackControl === false ) {
  19544. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19545. return;
  19546. }
  19547. this.source.stop();
  19548. this.startTime = 0;
  19549. this.isPlaying = false;
  19550. return this;
  19551. },
  19552. connect: function () {
  19553. if ( this.filters.length > 0 ) {
  19554. this.source.connect( this.filters[ 0 ] );
  19555. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19556. this.filters[ i - 1 ].connect( this.filters[ i ] );
  19557. }
  19558. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  19559. } else {
  19560. this.source.connect( this.getOutput() );
  19561. }
  19562. return this;
  19563. },
  19564. disconnect: function () {
  19565. if ( this.filters.length > 0 ) {
  19566. this.source.disconnect( this.filters[ 0 ] );
  19567. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19568. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  19569. }
  19570. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  19571. } else {
  19572. this.source.disconnect( this.getOutput() );
  19573. }
  19574. return this;
  19575. },
  19576. getFilters: function () {
  19577. return this.filters;
  19578. },
  19579. setFilters: function ( value ) {
  19580. if ( ! value ) value = [];
  19581. if ( this.isPlaying === true ) {
  19582. this.disconnect();
  19583. this.filters = value;
  19584. this.connect();
  19585. } else {
  19586. this.filters = value;
  19587. }
  19588. return this;
  19589. },
  19590. getFilter: function () {
  19591. return this.getFilters()[ 0 ];
  19592. },
  19593. setFilter: function ( filter ) {
  19594. return this.setFilters( filter ? [ filter ] : [] );
  19595. },
  19596. setPlaybackRate: function ( value ) {
  19597. if ( this.hasPlaybackControl === false ) {
  19598. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19599. return;
  19600. }
  19601. this.playbackRate = value;
  19602. if ( this.isPlaying === true ) {
  19603. this.source.playbackRate.value = this.playbackRate;
  19604. }
  19605. return this;
  19606. },
  19607. getPlaybackRate: function () {
  19608. return this.playbackRate;
  19609. },
  19610. onEnded: function () {
  19611. this.isPlaying = false;
  19612. },
  19613. getLoop: function () {
  19614. if ( this.hasPlaybackControl === false ) {
  19615. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19616. return false;
  19617. }
  19618. return this.source.loop;
  19619. },
  19620. setLoop: function ( value ) {
  19621. if ( this.hasPlaybackControl === false ) {
  19622. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19623. return;
  19624. }
  19625. this.source.loop = value;
  19626. },
  19627. getVolume: function () {
  19628. return this.gain.gain.value;
  19629. },
  19630. setVolume: function ( value ) {
  19631. this.gain.gain.value = value;
  19632. return this;
  19633. }
  19634. } );
  19635. function PositionalAudio( listener ) {
  19636. Audio.call( this, listener );
  19637. this.panner = this.context.createPanner();
  19638. this.panner.connect( this.gain );
  19639. }
  19640. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  19641. constructor: PositionalAudio,
  19642. getOutput: function () {
  19643. return this.panner;
  19644. },
  19645. getRefDistance: function () {
  19646. return this.panner.refDistance;
  19647. },
  19648. setRefDistance: function ( value ) {
  19649. this.panner.refDistance = value;
  19650. },
  19651. getRolloffFactor: function () {
  19652. return this.panner.rolloffFactor;
  19653. },
  19654. setRolloffFactor: function ( value ) {
  19655. this.panner.rolloffFactor = value;
  19656. },
  19657. getDistanceModel: function () {
  19658. return this.panner.distanceModel;
  19659. },
  19660. setDistanceModel: function ( value ) {
  19661. this.panner.distanceModel = value;
  19662. },
  19663. getMaxDistance: function () {
  19664. return this.panner.maxDistance;
  19665. },
  19666. setMaxDistance: function ( value ) {
  19667. this.panner.maxDistance = value;
  19668. },
  19669. updateMatrixWorld: ( function () {
  19670. var position = new Vector3();
  19671. return function updateMatrixWorld( force ) {
  19672. Object3D.prototype.updateMatrixWorld.call( this, force );
  19673. position.setFromMatrixPosition( this.matrixWorld );
  19674. this.panner.setPosition( position.x, position.y, position.z );
  19675. };
  19676. } )()
  19677. } );
  19678. /**
  19679. * @author mrdoob / http://mrdoob.com/
  19680. */
  19681. function AudioAnalyser( audio, fftSize ) {
  19682. this.analyser = audio.context.createAnalyser();
  19683. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  19684. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  19685. audio.getOutput().connect( this.analyser );
  19686. }
  19687. Object.assign( AudioAnalyser.prototype, {
  19688. getFrequencyData: function () {
  19689. this.analyser.getByteFrequencyData( this.data );
  19690. return this.data;
  19691. },
  19692. getAverageFrequency: function () {
  19693. var value = 0, data = this.getFrequencyData();
  19694. for ( var i = 0; i < data.length; i ++ ) {
  19695. value += data[ i ];
  19696. }
  19697. return value / data.length;
  19698. }
  19699. } );
  19700. /**
  19701. *
  19702. * Buffered scene graph property that allows weighted accumulation.
  19703. *
  19704. *
  19705. * @author Ben Houston / http://clara.io/
  19706. * @author David Sarno / http://lighthaus.us/
  19707. * @author tschw
  19708. */
  19709. function PropertyMixer( binding, typeName, valueSize ) {
  19710. this.binding = binding;
  19711. this.valueSize = valueSize;
  19712. var bufferType = Float64Array,
  19713. mixFunction;
  19714. switch ( typeName ) {
  19715. case 'quaternion': mixFunction = this._slerp; break;
  19716. case 'string':
  19717. case 'bool':
  19718. bufferType = Array, mixFunction = this._select; break;
  19719. default: mixFunction = this._lerp;
  19720. }
  19721. this.buffer = new bufferType( valueSize * 4 );
  19722. // layout: [ incoming | accu0 | accu1 | orig ]
  19723. //
  19724. // interpolators can use .buffer as their .result
  19725. // the data then goes to 'incoming'
  19726. //
  19727. // 'accu0' and 'accu1' are used frame-interleaved for
  19728. // the cumulative result and are compared to detect
  19729. // changes
  19730. //
  19731. // 'orig' stores the original state of the property
  19732. this._mixBufferRegion = mixFunction;
  19733. this.cumulativeWeight = 0;
  19734. this.useCount = 0;
  19735. this.referenceCount = 0;
  19736. }
  19737. PropertyMixer.prototype = {
  19738. constructor: PropertyMixer,
  19739. // accumulate data in the 'incoming' region into 'accu<i>'
  19740. accumulate: function( accuIndex, weight ) {
  19741. // note: happily accumulating nothing when weight = 0, the caller knows
  19742. // the weight and shouldn't have made the call in the first place
  19743. var buffer = this.buffer,
  19744. stride = this.valueSize,
  19745. offset = accuIndex * stride + stride,
  19746. currentWeight = this.cumulativeWeight;
  19747. if ( currentWeight === 0 ) {
  19748. // accuN := incoming * weight
  19749. for ( var i = 0; i !== stride; ++ i ) {
  19750. buffer[ offset + i ] = buffer[ i ];
  19751. }
  19752. currentWeight = weight;
  19753. } else {
  19754. // accuN := accuN + incoming * weight
  19755. currentWeight += weight;
  19756. var mix = weight / currentWeight;
  19757. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  19758. }
  19759. this.cumulativeWeight = currentWeight;
  19760. },
  19761. // apply the state of 'accu<i>' to the binding when accus differ
  19762. apply: function( accuIndex ) {
  19763. var stride = this.valueSize,
  19764. buffer = this.buffer,
  19765. offset = accuIndex * stride + stride,
  19766. weight = this.cumulativeWeight,
  19767. binding = this.binding;
  19768. this.cumulativeWeight = 0;
  19769. if ( weight < 1 ) {
  19770. // accuN := accuN + original * ( 1 - cumulativeWeight )
  19771. var originalValueOffset = stride * 3;
  19772. this._mixBufferRegion(
  19773. buffer, offset, originalValueOffset, 1 - weight, stride );
  19774. }
  19775. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  19776. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  19777. // value has changed -> update scene graph
  19778. binding.setValue( buffer, offset );
  19779. break;
  19780. }
  19781. }
  19782. },
  19783. // remember the state of the bound property and copy it to both accus
  19784. saveOriginalState: function() {
  19785. var binding = this.binding;
  19786. var buffer = this.buffer,
  19787. stride = this.valueSize,
  19788. originalValueOffset = stride * 3;
  19789. binding.getValue( buffer, originalValueOffset );
  19790. // accu[0..1] := orig -- initially detect changes against the original
  19791. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  19792. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  19793. }
  19794. this.cumulativeWeight = 0;
  19795. },
  19796. // apply the state previously taken via 'saveOriginalState' to the binding
  19797. restoreOriginalState: function() {
  19798. var originalValueOffset = this.valueSize * 3;
  19799. this.binding.setValue( this.buffer, originalValueOffset );
  19800. },
  19801. // mix functions
  19802. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  19803. if ( t >= 0.5 ) {
  19804. for ( var i = 0; i !== stride; ++ i ) {
  19805. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  19806. }
  19807. }
  19808. },
  19809. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19810. Quaternion.slerpFlat( buffer, dstOffset,
  19811. buffer, dstOffset, buffer, srcOffset, t );
  19812. },
  19813. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19814. var s = 1 - t;
  19815. for ( var i = 0; i !== stride; ++ i ) {
  19816. var j = dstOffset + i;
  19817. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  19818. }
  19819. }
  19820. };
  19821. /**
  19822. *
  19823. * A reference to a real property in the scene graph.
  19824. *
  19825. *
  19826. * @author Ben Houston / http://clara.io/
  19827. * @author David Sarno / http://lighthaus.us/
  19828. * @author tschw
  19829. */
  19830. function PropertyBinding( rootNode, path, parsedPath ) {
  19831. this.path = path;
  19832. this.parsedPath = parsedPath ||
  19833. PropertyBinding.parseTrackName( path );
  19834. this.node = PropertyBinding.findNode(
  19835. rootNode, this.parsedPath.nodeName ) || rootNode;
  19836. this.rootNode = rootNode;
  19837. }
  19838. PropertyBinding.prototype = {
  19839. constructor: PropertyBinding,
  19840. getValue: function getValue_unbound( targetArray, offset ) {
  19841. this.bind();
  19842. this.getValue( targetArray, offset );
  19843. // Note: This class uses a State pattern on a per-method basis:
  19844. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  19845. // prototype version of these methods with one that represents
  19846. // the bound state. When the property is not found, the methods
  19847. // become no-ops.
  19848. },
  19849. setValue: function getValue_unbound( sourceArray, offset ) {
  19850. this.bind();
  19851. this.setValue( sourceArray, offset );
  19852. },
  19853. // create getter / setter pair for a property in the scene graph
  19854. bind: function() {
  19855. var targetObject = this.node,
  19856. parsedPath = this.parsedPath,
  19857. objectName = parsedPath.objectName,
  19858. propertyName = parsedPath.propertyName,
  19859. propertyIndex = parsedPath.propertyIndex;
  19860. if ( ! targetObject ) {
  19861. targetObject = PropertyBinding.findNode(
  19862. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  19863. this.node = targetObject;
  19864. }
  19865. // set fail state so we can just 'return' on error
  19866. this.getValue = this._getValue_unavailable;
  19867. this.setValue = this._setValue_unavailable;
  19868. // ensure there is a value node
  19869. if ( ! targetObject ) {
  19870. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  19871. return;
  19872. }
  19873. if ( objectName ) {
  19874. var objectIndex = parsedPath.objectIndex;
  19875. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  19876. switch ( objectName ) {
  19877. case 'materials':
  19878. if ( ! targetObject.material ) {
  19879. console.error( ' can not bind to material as node does not have a material', this );
  19880. return;
  19881. }
  19882. if ( ! targetObject.material.materials ) {
  19883. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  19884. return;
  19885. }
  19886. targetObject = targetObject.material.materials;
  19887. break;
  19888. case 'bones':
  19889. if ( ! targetObject.skeleton ) {
  19890. console.error( ' can not bind to bones as node does not have a skeleton', this );
  19891. return;
  19892. }
  19893. // potential future optimization: skip this if propertyIndex is already an integer
  19894. // and convert the integer string to a true integer.
  19895. targetObject = targetObject.skeleton.bones;
  19896. // support resolving morphTarget names into indices.
  19897. for ( var i = 0; i < targetObject.length; i ++ ) {
  19898. if ( targetObject[ i ].name === objectIndex ) {
  19899. objectIndex = i;
  19900. break;
  19901. }
  19902. }
  19903. break;
  19904. default:
  19905. if ( targetObject[ objectName ] === undefined ) {
  19906. console.error( ' can not bind to objectName of node, undefined', this );
  19907. return;
  19908. }
  19909. targetObject = targetObject[ objectName ];
  19910. }
  19911. if ( objectIndex !== undefined ) {
  19912. if ( targetObject[ objectIndex ] === undefined ) {
  19913. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  19914. return;
  19915. }
  19916. targetObject = targetObject[ objectIndex ];
  19917. }
  19918. }
  19919. // resolve property
  19920. var nodeProperty = targetObject[ propertyName ];
  19921. if ( nodeProperty === undefined ) {
  19922. var nodeName = parsedPath.nodeName;
  19923. console.error( " trying to update property for track: " + nodeName +
  19924. '.' + propertyName + " but it wasn't found.", targetObject );
  19925. return;
  19926. }
  19927. // determine versioning scheme
  19928. var versioning = this.Versioning.None;
  19929. if ( targetObject.needsUpdate !== undefined ) { // material
  19930. versioning = this.Versioning.NeedsUpdate;
  19931. this.targetObject = targetObject;
  19932. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19933. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19934. this.targetObject = targetObject;
  19935. }
  19936. // determine how the property gets bound
  19937. var bindingType = this.BindingType.Direct;
  19938. if ( propertyIndex !== undefined ) {
  19939. // access a sub element of the property array (only primitives are supported right now)
  19940. if ( propertyName === "morphTargetInfluences" ) {
  19941. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19942. // support resolving morphTarget names into indices.
  19943. if ( ! targetObject.geometry ) {
  19944. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  19945. return;
  19946. }
  19947. if ( ! targetObject.geometry.morphTargets ) {
  19948. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  19949. return;
  19950. }
  19951. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  19952. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  19953. propertyIndex = i;
  19954. break;
  19955. }
  19956. }
  19957. }
  19958. bindingType = this.BindingType.ArrayElement;
  19959. this.resolvedProperty = nodeProperty;
  19960. this.propertyIndex = propertyIndex;
  19961. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19962. // must use copy for Object3D.Euler/Quaternion
  19963. bindingType = this.BindingType.HasFromToArray;
  19964. this.resolvedProperty = nodeProperty;
  19965. } else if ( nodeProperty.length !== undefined ) {
  19966. bindingType = this.BindingType.EntireArray;
  19967. this.resolvedProperty = nodeProperty;
  19968. } else {
  19969. this.propertyName = propertyName;
  19970. }
  19971. // select getter / setter
  19972. this.getValue = this.GetterByBindingType[ bindingType ];
  19973. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19974. },
  19975. unbind: function() {
  19976. this.node = null;
  19977. // back to the prototype version of getValue / setValue
  19978. // note: avoiding to mutate the shape of 'this' via 'delete'
  19979. this.getValue = this._getValue_unbound;
  19980. this.setValue = this._setValue_unbound;
  19981. }
  19982. };
  19983. Object.assign( PropertyBinding.prototype, { // prototype, continued
  19984. // these are used to "bind" a nonexistent property
  19985. _getValue_unavailable: function() {},
  19986. _setValue_unavailable: function() {},
  19987. // initial state of these methods that calls 'bind'
  19988. _getValue_unbound: PropertyBinding.prototype.getValue,
  19989. _setValue_unbound: PropertyBinding.prototype.setValue,
  19990. BindingType: {
  19991. Direct: 0,
  19992. EntireArray: 1,
  19993. ArrayElement: 2,
  19994. HasFromToArray: 3
  19995. },
  19996. Versioning: {
  19997. None: 0,
  19998. NeedsUpdate: 1,
  19999. MatrixWorldNeedsUpdate: 2
  20000. },
  20001. GetterByBindingType: [
  20002. function getValue_direct( buffer, offset ) {
  20003. buffer[ offset ] = this.node[ this.propertyName ];
  20004. },
  20005. function getValue_array( buffer, offset ) {
  20006. var source = this.resolvedProperty;
  20007. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  20008. buffer[ offset ++ ] = source[ i ];
  20009. }
  20010. },
  20011. function getValue_arrayElement( buffer, offset ) {
  20012. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  20013. },
  20014. function getValue_toArray( buffer, offset ) {
  20015. this.resolvedProperty.toArray( buffer, offset );
  20016. }
  20017. ],
  20018. SetterByBindingTypeAndVersioning: [
  20019. [
  20020. // Direct
  20021. function setValue_direct( buffer, offset ) {
  20022. this.node[ this.propertyName ] = buffer[ offset ];
  20023. },
  20024. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  20025. this.node[ this.propertyName ] = buffer[ offset ];
  20026. this.targetObject.needsUpdate = true;
  20027. },
  20028. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20029. this.node[ this.propertyName ] = buffer[ offset ];
  20030. this.targetObject.matrixWorldNeedsUpdate = true;
  20031. }
  20032. ], [
  20033. // EntireArray
  20034. function setValue_array( buffer, offset ) {
  20035. var dest = this.resolvedProperty;
  20036. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20037. dest[ i ] = buffer[ offset ++ ];
  20038. }
  20039. },
  20040. function setValue_array_setNeedsUpdate( buffer, offset ) {
  20041. var dest = this.resolvedProperty;
  20042. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20043. dest[ i ] = buffer[ offset ++ ];
  20044. }
  20045. this.targetObject.needsUpdate = true;
  20046. },
  20047. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20048. var dest = this.resolvedProperty;
  20049. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  20050. dest[ i ] = buffer[ offset ++ ];
  20051. }
  20052. this.targetObject.matrixWorldNeedsUpdate = true;
  20053. }
  20054. ], [
  20055. // ArrayElement
  20056. function setValue_arrayElement( buffer, offset ) {
  20057. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20058. },
  20059. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  20060. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20061. this.targetObject.needsUpdate = true;
  20062. },
  20063. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20064. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20065. this.targetObject.matrixWorldNeedsUpdate = true;
  20066. }
  20067. ], [
  20068. // HasToFromArray
  20069. function setValue_fromArray( buffer, offset ) {
  20070. this.resolvedProperty.fromArray( buffer, offset );
  20071. },
  20072. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  20073. this.resolvedProperty.fromArray( buffer, offset );
  20074. this.targetObject.needsUpdate = true;
  20075. },
  20076. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20077. this.resolvedProperty.fromArray( buffer, offset );
  20078. this.targetObject.matrixWorldNeedsUpdate = true;
  20079. }
  20080. ]
  20081. ]
  20082. } );
  20083. PropertyBinding.Composite =
  20084. function( targetGroup, path, optionalParsedPath ) {
  20085. var parsedPath = optionalParsedPath ||
  20086. PropertyBinding.parseTrackName( path );
  20087. this._targetGroup = targetGroup;
  20088. this._bindings = targetGroup.subscribe_( path, parsedPath );
  20089. };
  20090. PropertyBinding.Composite.prototype = {
  20091. constructor: PropertyBinding.Composite,
  20092. getValue: function( array, offset ) {
  20093. this.bind(); // bind all binding
  20094. var firstValidIndex = this._targetGroup.nCachedObjects_,
  20095. binding = this._bindings[ firstValidIndex ];
  20096. // and only call .getValue on the first
  20097. if ( binding !== undefined ) binding.getValue( array, offset );
  20098. },
  20099. setValue: function( array, offset ) {
  20100. var bindings = this._bindings;
  20101. for ( var i = this._targetGroup.nCachedObjects_,
  20102. n = bindings.length; i !== n; ++ i ) {
  20103. bindings[ i ].setValue( array, offset );
  20104. }
  20105. },
  20106. bind: function() {
  20107. var bindings = this._bindings;
  20108. for ( var i = this._targetGroup.nCachedObjects_,
  20109. n = bindings.length; i !== n; ++ i ) {
  20110. bindings[ i ].bind();
  20111. }
  20112. },
  20113. unbind: function() {
  20114. var bindings = this._bindings;
  20115. for ( var i = this._targetGroup.nCachedObjects_,
  20116. n = bindings.length; i !== n; ++ i ) {
  20117. bindings[ i ].unbind();
  20118. }
  20119. }
  20120. };
  20121. PropertyBinding.create = function( root, path, parsedPath ) {
  20122. if ( ! ( (root && root.isAnimationObjectGroup) ) ) {
  20123. return new PropertyBinding( root, path, parsedPath );
  20124. } else {
  20125. return new PropertyBinding.Composite( root, path, parsedPath );
  20126. }
  20127. };
  20128. PropertyBinding.parseTrackName = function( trackName ) {
  20129. // matches strings in the form of:
  20130. // nodeName.property
  20131. // nodeName.property[accessor]
  20132. // nodeName.material.property[accessor]
  20133. // uuid.property[accessor]
  20134. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  20135. // parentName/nodeName.property
  20136. // parentName/parentName/nodeName.property[index]
  20137. // .bone[Armature.DEF_cog].position
  20138. // created and tested via https://regex101.com/#javascript
  20139. var re = /^((?:\w+\/)*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/;
  20140. var matches = re.exec( trackName );
  20141. if ( ! matches ) {
  20142. throw new Error( "cannot parse trackName at all: " + trackName );
  20143. }
  20144. var results = {
  20145. // directoryName: matches[ 1 ], // (tschw) currently unused
  20146. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  20147. objectName: matches[ 3 ],
  20148. objectIndex: matches[ 4 ],
  20149. propertyName: matches[ 5 ],
  20150. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  20151. };
  20152. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  20153. throw new Error( "can not parse propertyName from trackName: " + trackName );
  20154. }
  20155. return results;
  20156. };
  20157. PropertyBinding.findNode = function( root, nodeName ) {
  20158. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  20159. return root;
  20160. }
  20161. // search into skeleton bones.
  20162. if ( root.skeleton ) {
  20163. var searchSkeleton = function( skeleton ) {
  20164. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  20165. var bone = skeleton.bones[ i ];
  20166. if ( bone.name === nodeName ) {
  20167. return bone;
  20168. }
  20169. }
  20170. return null;
  20171. };
  20172. var bone = searchSkeleton( root.skeleton );
  20173. if ( bone ) {
  20174. return bone;
  20175. }
  20176. }
  20177. // search into node subtree.
  20178. if ( root.children ) {
  20179. var searchNodeSubtree = function( children ) {
  20180. for( var i = 0; i < children.length; i ++ ) {
  20181. var childNode = children[ i ];
  20182. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  20183. return childNode;
  20184. }
  20185. var result = searchNodeSubtree( childNode.children );
  20186. if ( result ) return result;
  20187. }
  20188. return null;
  20189. };
  20190. var subTreeNode = searchNodeSubtree( root.children );
  20191. if ( subTreeNode ) {
  20192. return subTreeNode;
  20193. }
  20194. }
  20195. return null;
  20196. };
  20197. /**
  20198. *
  20199. * A group of objects that receives a shared animation state.
  20200. *
  20201. * Usage:
  20202. *
  20203. * - Add objects you would otherwise pass as 'root' to the
  20204. * constructor or the .clipAction method of AnimationMixer.
  20205. *
  20206. * - Instead pass this object as 'root'.
  20207. *
  20208. * - You can also add and remove objects later when the mixer
  20209. * is running.
  20210. *
  20211. * Note:
  20212. *
  20213. * Objects of this class appear as one object to the mixer,
  20214. * so cache control of the individual objects must be done
  20215. * on the group.
  20216. *
  20217. * Limitation:
  20218. *
  20219. * - The animated properties must be compatible among the
  20220. * all objects in the group.
  20221. *
  20222. * - A single property can either be controlled through a
  20223. * target group or directly, but not both.
  20224. *
  20225. * @author tschw
  20226. */
  20227. function AnimationObjectGroup( var_args ) {
  20228. this.uuid = exports.Math.generateUUID();
  20229. // cached objects followed by the active ones
  20230. this._objects = Array.prototype.slice.call( arguments );
  20231. this.nCachedObjects_ = 0; // threshold
  20232. // note: read by PropertyBinding.Composite
  20233. var indices = {};
  20234. this._indicesByUUID = indices; // for bookkeeping
  20235. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20236. indices[ arguments[ i ].uuid ] = i;
  20237. }
  20238. this._paths = []; // inside: string
  20239. this._parsedPaths = []; // inside: { we don't care, here }
  20240. this._bindings = []; // inside: Array< PropertyBinding >
  20241. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  20242. var scope = this;
  20243. this.stats = {
  20244. objects: {
  20245. get total() { return scope._objects.length; },
  20246. get inUse() { return this.total - scope.nCachedObjects_; }
  20247. },
  20248. get bindingsPerObject() { return scope._bindings.length; }
  20249. };
  20250. }
  20251. AnimationObjectGroup.prototype = {
  20252. constructor: AnimationObjectGroup,
  20253. isAnimationObjectGroup: true,
  20254. add: function( var_args ) {
  20255. var objects = this._objects,
  20256. nObjects = objects.length,
  20257. nCachedObjects = this.nCachedObjects_,
  20258. indicesByUUID = this._indicesByUUID,
  20259. paths = this._paths,
  20260. parsedPaths = this._parsedPaths,
  20261. bindings = this._bindings,
  20262. nBindings = bindings.length;
  20263. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20264. var object = arguments[ i ],
  20265. uuid = object.uuid,
  20266. index = indicesByUUID[ uuid ];
  20267. if ( index === undefined ) {
  20268. // unknown object -> add it to the ACTIVE region
  20269. index = nObjects ++;
  20270. indicesByUUID[ uuid ] = index;
  20271. objects.push( object );
  20272. // accounting is done, now do the same for all bindings
  20273. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20274. bindings[ j ].push(
  20275. new PropertyBinding(
  20276. object, paths[ j ], parsedPaths[ j ] ) );
  20277. }
  20278. } else if ( index < nCachedObjects ) {
  20279. var knownObject = objects[ index ];
  20280. // move existing object to the ACTIVE region
  20281. var firstActiveIndex = -- nCachedObjects,
  20282. lastCachedObject = objects[ firstActiveIndex ];
  20283. indicesByUUID[ lastCachedObject.uuid ] = index;
  20284. objects[ index ] = lastCachedObject;
  20285. indicesByUUID[ uuid ] = firstActiveIndex;
  20286. objects[ firstActiveIndex ] = object;
  20287. // accounting is done, now do the same for all bindings
  20288. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20289. var bindingsForPath = bindings[ j ],
  20290. lastCached = bindingsForPath[ firstActiveIndex ],
  20291. binding = bindingsForPath[ index ];
  20292. bindingsForPath[ index ] = lastCached;
  20293. if ( binding === undefined ) {
  20294. // since we do not bother to create new bindings
  20295. // for objects that are cached, the binding may
  20296. // or may not exist
  20297. binding = new PropertyBinding(
  20298. object, paths[ j ], parsedPaths[ j ] );
  20299. }
  20300. bindingsForPath[ firstActiveIndex ] = binding;
  20301. }
  20302. } else if ( objects[ index ] !== knownObject) {
  20303. console.error( "Different objects with the same UUID " +
  20304. "detected. Clean the caches or recreate your " +
  20305. "infrastructure when reloading scenes..." );
  20306. } // else the object is already where we want it to be
  20307. } // for arguments
  20308. this.nCachedObjects_ = nCachedObjects;
  20309. },
  20310. remove: function( var_args ) {
  20311. var objects = this._objects,
  20312. nCachedObjects = this.nCachedObjects_,
  20313. indicesByUUID = this._indicesByUUID,
  20314. bindings = this._bindings,
  20315. nBindings = bindings.length;
  20316. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20317. var object = arguments[ i ],
  20318. uuid = object.uuid,
  20319. index = indicesByUUID[ uuid ];
  20320. if ( index !== undefined && index >= nCachedObjects ) {
  20321. // move existing object into the CACHED region
  20322. var lastCachedIndex = nCachedObjects ++,
  20323. firstActiveObject = objects[ lastCachedIndex ];
  20324. indicesByUUID[ firstActiveObject.uuid ] = index;
  20325. objects[ index ] = firstActiveObject;
  20326. indicesByUUID[ uuid ] = lastCachedIndex;
  20327. objects[ lastCachedIndex ] = object;
  20328. // accounting is done, now do the same for all bindings
  20329. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20330. var bindingsForPath = bindings[ j ],
  20331. firstActive = bindingsForPath[ lastCachedIndex ],
  20332. binding = bindingsForPath[ index ];
  20333. bindingsForPath[ index ] = firstActive;
  20334. bindingsForPath[ lastCachedIndex ] = binding;
  20335. }
  20336. }
  20337. } // for arguments
  20338. this.nCachedObjects_ = nCachedObjects;
  20339. },
  20340. // remove & forget
  20341. uncache: function( var_args ) {
  20342. var objects = this._objects,
  20343. nObjects = objects.length,
  20344. nCachedObjects = this.nCachedObjects_,
  20345. indicesByUUID = this._indicesByUUID,
  20346. bindings = this._bindings,
  20347. nBindings = bindings.length;
  20348. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20349. var object = arguments[ i ],
  20350. uuid = object.uuid,
  20351. index = indicesByUUID[ uuid ];
  20352. if ( index !== undefined ) {
  20353. delete indicesByUUID[ uuid ];
  20354. if ( index < nCachedObjects ) {
  20355. // object is cached, shrink the CACHED region
  20356. var firstActiveIndex = -- nCachedObjects,
  20357. lastCachedObject = objects[ firstActiveIndex ],
  20358. lastIndex = -- nObjects,
  20359. lastObject = objects[ lastIndex ];
  20360. // last cached object takes this object's place
  20361. indicesByUUID[ lastCachedObject.uuid ] = index;
  20362. objects[ index ] = lastCachedObject;
  20363. // last object goes to the activated slot and pop
  20364. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  20365. objects[ firstActiveIndex ] = lastObject;
  20366. objects.pop();
  20367. // accounting is done, now do the same for all bindings
  20368. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20369. var bindingsForPath = bindings[ j ],
  20370. lastCached = bindingsForPath[ firstActiveIndex ],
  20371. last = bindingsForPath[ lastIndex ];
  20372. bindingsForPath[ index ] = lastCached;
  20373. bindingsForPath[ firstActiveIndex ] = last;
  20374. bindingsForPath.pop();
  20375. }
  20376. } else {
  20377. // object is active, just swap with the last and pop
  20378. var lastIndex = -- nObjects,
  20379. lastObject = objects[ lastIndex ];
  20380. indicesByUUID[ lastObject.uuid ] = index;
  20381. objects[ index ] = lastObject;
  20382. objects.pop();
  20383. // accounting is done, now do the same for all bindings
  20384. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20385. var bindingsForPath = bindings[ j ];
  20386. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  20387. bindingsForPath.pop();
  20388. }
  20389. } // cached or active
  20390. } // if object is known
  20391. } // for arguments
  20392. this.nCachedObjects_ = nCachedObjects;
  20393. },
  20394. // Internal interface used by befriended PropertyBinding.Composite:
  20395. subscribe_: function( path, parsedPath ) {
  20396. // returns an array of bindings for the given path that is changed
  20397. // according to the contained objects in the group
  20398. var indicesByPath = this._bindingsIndicesByPath,
  20399. index = indicesByPath[ path ],
  20400. bindings = this._bindings;
  20401. if ( index !== undefined ) return bindings[ index ];
  20402. var paths = this._paths,
  20403. parsedPaths = this._parsedPaths,
  20404. objects = this._objects,
  20405. nObjects = objects.length,
  20406. nCachedObjects = this.nCachedObjects_,
  20407. bindingsForPath = new Array( nObjects );
  20408. index = bindings.length;
  20409. indicesByPath[ path ] = index;
  20410. paths.push( path );
  20411. parsedPaths.push( parsedPath );
  20412. bindings.push( bindingsForPath );
  20413. for ( var i = nCachedObjects,
  20414. n = objects.length; i !== n; ++ i ) {
  20415. var object = objects[ i ];
  20416. bindingsForPath[ i ] =
  20417. new PropertyBinding( object, path, parsedPath );
  20418. }
  20419. return bindingsForPath;
  20420. },
  20421. unsubscribe_: function( path ) {
  20422. // tells the group to forget about a property path and no longer
  20423. // update the array previously obtained with 'subscribe_'
  20424. var indicesByPath = this._bindingsIndicesByPath,
  20425. index = indicesByPath[ path ];
  20426. if ( index !== undefined ) {
  20427. var paths = this._paths,
  20428. parsedPaths = this._parsedPaths,
  20429. bindings = this._bindings,
  20430. lastBindingsIndex = bindings.length - 1,
  20431. lastBindings = bindings[ lastBindingsIndex ],
  20432. lastBindingsPath = path[ lastBindingsIndex ];
  20433. indicesByPath[ lastBindingsPath ] = index;
  20434. bindings[ index ] = lastBindings;
  20435. bindings.pop();
  20436. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  20437. parsedPaths.pop();
  20438. paths[ index ] = paths[ lastBindingsIndex ];
  20439. paths.pop();
  20440. }
  20441. }
  20442. };
  20443. /**
  20444. *
  20445. * Action provided by AnimationMixer for scheduling clip playback on specific
  20446. * objects.
  20447. *
  20448. * @author Ben Houston / http://clara.io/
  20449. * @author David Sarno / http://lighthaus.us/
  20450. * @author tschw
  20451. *
  20452. */
  20453. function AnimationAction( mixer, clip, localRoot ) {
  20454. this._mixer = mixer;
  20455. this._clip = clip;
  20456. this._localRoot = localRoot || null;
  20457. var tracks = clip.tracks,
  20458. nTracks = tracks.length,
  20459. interpolants = new Array( nTracks );
  20460. var interpolantSettings = {
  20461. endingStart: ZeroCurvatureEnding,
  20462. endingEnd: ZeroCurvatureEnding
  20463. };
  20464. for ( var i = 0; i !== nTracks; ++ i ) {
  20465. var interpolant = tracks[ i ].createInterpolant( null );
  20466. interpolants[ i ] = interpolant;
  20467. interpolant.settings = interpolantSettings;
  20468. }
  20469. this._interpolantSettings = interpolantSettings;
  20470. this._interpolants = interpolants; // bound by the mixer
  20471. // inside: PropertyMixer (managed by the mixer)
  20472. this._propertyBindings = new Array( nTracks );
  20473. this._cacheIndex = null; // for the memory manager
  20474. this._byClipCacheIndex = null; // for the memory manager
  20475. this._timeScaleInterpolant = null;
  20476. this._weightInterpolant = null;
  20477. this.loop = LoopRepeat;
  20478. this._loopCount = -1;
  20479. // global mixer time when the action is to be started
  20480. // it's set back to 'null' upon start of the action
  20481. this._startTime = null;
  20482. // scaled local time of the action
  20483. // gets clamped or wrapped to 0..clip.duration according to loop
  20484. this.time = 0;
  20485. this.timeScale = 1;
  20486. this._effectiveTimeScale = 1;
  20487. this.weight = 1;
  20488. this._effectiveWeight = 1;
  20489. this.repetitions = Infinity; // no. of repetitions when looping
  20490. this.paused = false; // false -> zero effective time scale
  20491. this.enabled = true; // true -> zero effective weight
  20492. this.clampWhenFinished = false; // keep feeding the last frame?
  20493. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  20494. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  20495. };
  20496. AnimationAction.prototype = {
  20497. constructor: AnimationAction,
  20498. // State & Scheduling
  20499. play: function() {
  20500. this._mixer._activateAction( this );
  20501. return this;
  20502. },
  20503. stop: function() {
  20504. this._mixer._deactivateAction( this );
  20505. return this.reset();
  20506. },
  20507. reset: function() {
  20508. this.paused = false;
  20509. this.enabled = true;
  20510. this.time = 0; // restart clip
  20511. this._loopCount = -1; // forget previous loops
  20512. this._startTime = null; // forget scheduling
  20513. return this.stopFading().stopWarping();
  20514. },
  20515. isRunning: function() {
  20516. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  20517. this._startTime === null && this._mixer._isActiveAction( this );
  20518. },
  20519. // return true when play has been called
  20520. isScheduled: function() {
  20521. return this._mixer._isActiveAction( this );
  20522. },
  20523. startAt: function( time ) {
  20524. this._startTime = time;
  20525. return this;
  20526. },
  20527. setLoop: function( mode, repetitions ) {
  20528. this.loop = mode;
  20529. this.repetitions = repetitions;
  20530. return this;
  20531. },
  20532. // Weight
  20533. // set the weight stopping any scheduled fading
  20534. // although .enabled = false yields an effective weight of zero, this
  20535. // method does *not* change .enabled, because it would be confusing
  20536. setEffectiveWeight: function( weight ) {
  20537. this.weight = weight;
  20538. // note: same logic as when updated at runtime
  20539. this._effectiveWeight = this.enabled ? weight : 0;
  20540. return this.stopFading();
  20541. },
  20542. // return the weight considering fading and .enabled
  20543. getEffectiveWeight: function() {
  20544. return this._effectiveWeight;
  20545. },
  20546. fadeIn: function( duration ) {
  20547. return this._scheduleFading( duration, 0, 1 );
  20548. },
  20549. fadeOut: function( duration ) {
  20550. return this._scheduleFading( duration, 1, 0 );
  20551. },
  20552. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  20553. fadeOutAction.fadeOut( duration );
  20554. this.fadeIn( duration );
  20555. if( warp ) {
  20556. var fadeInDuration = this._clip.duration,
  20557. fadeOutDuration = fadeOutAction._clip.duration,
  20558. startEndRatio = fadeOutDuration / fadeInDuration,
  20559. endStartRatio = fadeInDuration / fadeOutDuration;
  20560. fadeOutAction.warp( 1.0, startEndRatio, duration );
  20561. this.warp( endStartRatio, 1.0, duration );
  20562. }
  20563. return this;
  20564. },
  20565. crossFadeTo: function( fadeInAction, duration, warp ) {
  20566. return fadeInAction.crossFadeFrom( this, duration, warp );
  20567. },
  20568. stopFading: function() {
  20569. var weightInterpolant = this._weightInterpolant;
  20570. if ( weightInterpolant !== null ) {
  20571. this._weightInterpolant = null;
  20572. this._mixer._takeBackControlInterpolant( weightInterpolant );
  20573. }
  20574. return this;
  20575. },
  20576. // Time Scale Control
  20577. // set the weight stopping any scheduled warping
  20578. // although .paused = true yields an effective time scale of zero, this
  20579. // method does *not* change .paused, because it would be confusing
  20580. setEffectiveTimeScale: function( timeScale ) {
  20581. this.timeScale = timeScale;
  20582. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  20583. return this.stopWarping();
  20584. },
  20585. // return the time scale considering warping and .paused
  20586. getEffectiveTimeScale: function() {
  20587. return this._effectiveTimeScale;
  20588. },
  20589. setDuration: function( duration ) {
  20590. this.timeScale = this._clip.duration / duration;
  20591. return this.stopWarping();
  20592. },
  20593. syncWith: function( action ) {
  20594. this.time = action.time;
  20595. this.timeScale = action.timeScale;
  20596. return this.stopWarping();
  20597. },
  20598. halt: function( duration ) {
  20599. return this.warp( this._effectiveTimeScale, 0, duration );
  20600. },
  20601. warp: function( startTimeScale, endTimeScale, duration ) {
  20602. var mixer = this._mixer, now = mixer.time,
  20603. interpolant = this._timeScaleInterpolant,
  20604. timeScale = this.timeScale;
  20605. if ( interpolant === null ) {
  20606. interpolant = mixer._lendControlInterpolant(),
  20607. this._timeScaleInterpolant = interpolant;
  20608. }
  20609. var times = interpolant.parameterPositions,
  20610. values = interpolant.sampleValues;
  20611. times[ 0 ] = now;
  20612. times[ 1 ] = now + duration;
  20613. values[ 0 ] = startTimeScale / timeScale;
  20614. values[ 1 ] = endTimeScale / timeScale;
  20615. return this;
  20616. },
  20617. stopWarping: function() {
  20618. var timeScaleInterpolant = this._timeScaleInterpolant;
  20619. if ( timeScaleInterpolant !== null ) {
  20620. this._timeScaleInterpolant = null;
  20621. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  20622. }
  20623. return this;
  20624. },
  20625. // Object Accessors
  20626. getMixer: function() {
  20627. return this._mixer;
  20628. },
  20629. getClip: function() {
  20630. return this._clip;
  20631. },
  20632. getRoot: function() {
  20633. return this._localRoot || this._mixer._root;
  20634. },
  20635. // Interna
  20636. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  20637. // called by the mixer
  20638. var startTime = this._startTime;
  20639. if ( startTime !== null ) {
  20640. // check for scheduled start of action
  20641. var timeRunning = ( time - startTime ) * timeDirection;
  20642. if ( timeRunning < 0 || timeDirection === 0 ) {
  20643. return; // yet to come / don't decide when delta = 0
  20644. }
  20645. // start
  20646. this._startTime = null; // unschedule
  20647. deltaTime = timeDirection * timeRunning;
  20648. }
  20649. // apply time scale and advance time
  20650. deltaTime *= this._updateTimeScale( time );
  20651. var clipTime = this._updateTime( deltaTime );
  20652. // note: _updateTime may disable the action resulting in
  20653. // an effective weight of 0
  20654. var weight = this._updateWeight( time );
  20655. if ( weight > 0 ) {
  20656. var interpolants = this._interpolants;
  20657. var propertyMixers = this._propertyBindings;
  20658. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  20659. interpolants[ j ].evaluate( clipTime );
  20660. propertyMixers[ j ].accumulate( accuIndex, weight );
  20661. }
  20662. }
  20663. },
  20664. _updateWeight: function( time ) {
  20665. var weight = 0;
  20666. if ( this.enabled ) {
  20667. weight = this.weight;
  20668. var interpolant = this._weightInterpolant;
  20669. if ( interpolant !== null ) {
  20670. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20671. weight *= interpolantValue;
  20672. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20673. this.stopFading();
  20674. if ( interpolantValue === 0 ) {
  20675. // faded out, disable
  20676. this.enabled = false;
  20677. }
  20678. }
  20679. }
  20680. }
  20681. this._effectiveWeight = weight;
  20682. return weight;
  20683. },
  20684. _updateTimeScale: function( time ) {
  20685. var timeScale = 0;
  20686. if ( ! this.paused ) {
  20687. timeScale = this.timeScale;
  20688. var interpolant = this._timeScaleInterpolant;
  20689. if ( interpolant !== null ) {
  20690. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20691. timeScale *= interpolantValue;
  20692. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20693. this.stopWarping();
  20694. if ( timeScale === 0 ) {
  20695. // motion has halted, pause
  20696. this.paused = true;
  20697. } else {
  20698. // warp done - apply final time scale
  20699. this.timeScale = timeScale;
  20700. }
  20701. }
  20702. }
  20703. }
  20704. this._effectiveTimeScale = timeScale;
  20705. return timeScale;
  20706. },
  20707. _updateTime: function( deltaTime ) {
  20708. var time = this.time + deltaTime;
  20709. if ( deltaTime === 0 ) return time;
  20710. var duration = this._clip.duration,
  20711. loop = this.loop,
  20712. loopCount = this._loopCount;
  20713. if ( loop === LoopOnce ) {
  20714. if ( loopCount === -1 ) {
  20715. // just started
  20716. this.loopCount = 0;
  20717. this._setEndings( true, true, false );
  20718. }
  20719. handle_stop: {
  20720. if ( time >= duration ) {
  20721. time = duration;
  20722. } else if ( time < 0 ) {
  20723. time = 0;
  20724. } else break handle_stop;
  20725. if ( this.clampWhenFinished ) this.paused = true;
  20726. else this.enabled = false;
  20727. this._mixer.dispatchEvent( {
  20728. type: 'finished', action: this,
  20729. direction: deltaTime < 0 ? -1 : 1
  20730. } );
  20731. }
  20732. } else { // repetitive Repeat or PingPong
  20733. var pingPong = ( loop === LoopPingPong );
  20734. if ( loopCount === -1 ) {
  20735. // just started
  20736. if ( deltaTime >= 0 ) {
  20737. loopCount = 0;
  20738. this._setEndings(
  20739. true, this.repetitions === 0, pingPong );
  20740. } else {
  20741. // when looping in reverse direction, the initial
  20742. // transition through zero counts as a repetition,
  20743. // so leave loopCount at -1
  20744. this._setEndings(
  20745. this.repetitions === 0, true, pingPong );
  20746. }
  20747. }
  20748. if ( time >= duration || time < 0 ) {
  20749. // wrap around
  20750. var loopDelta = Math.floor( time / duration ); // signed
  20751. time -= duration * loopDelta;
  20752. loopCount += Math.abs( loopDelta );
  20753. var pending = this.repetitions - loopCount;
  20754. if ( pending < 0 ) {
  20755. // have to stop (switch state, clamp time, fire event)
  20756. if ( this.clampWhenFinished ) this.paused = true;
  20757. else this.enabled = false;
  20758. time = deltaTime > 0 ? duration : 0;
  20759. this._mixer.dispatchEvent( {
  20760. type: 'finished', action: this,
  20761. direction: deltaTime > 0 ? 1 : -1
  20762. } );
  20763. } else {
  20764. // keep running
  20765. if ( pending === 0 ) {
  20766. // entering the last round
  20767. var atStart = deltaTime < 0;
  20768. this._setEndings( atStart, ! atStart, pingPong );
  20769. } else {
  20770. this._setEndings( false, false, pingPong );
  20771. }
  20772. this._loopCount = loopCount;
  20773. this._mixer.dispatchEvent( {
  20774. type: 'loop', action: this, loopDelta: loopDelta
  20775. } );
  20776. }
  20777. }
  20778. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  20779. // invert time for the "pong round"
  20780. this.time = time;
  20781. return duration - time;
  20782. }
  20783. }
  20784. this.time = time;
  20785. return time;
  20786. },
  20787. _setEndings: function( atStart, atEnd, pingPong ) {
  20788. var settings = this._interpolantSettings;
  20789. if ( pingPong ) {
  20790. settings.endingStart = ZeroSlopeEnding;
  20791. settings.endingEnd = ZeroSlopeEnding;
  20792. } else {
  20793. // assuming for LoopOnce atStart == atEnd == true
  20794. if ( atStart ) {
  20795. settings.endingStart = this.zeroSlopeAtStart ?
  20796. ZeroSlopeEnding : ZeroCurvatureEnding;
  20797. } else {
  20798. settings.endingStart = WrapAroundEnding;
  20799. }
  20800. if ( atEnd ) {
  20801. settings.endingEnd = this.zeroSlopeAtEnd ?
  20802. ZeroSlopeEnding : ZeroCurvatureEnding;
  20803. } else {
  20804. settings.endingEnd = WrapAroundEnding;
  20805. }
  20806. }
  20807. },
  20808. _scheduleFading: function( duration, weightNow, weightThen ) {
  20809. var mixer = this._mixer, now = mixer.time,
  20810. interpolant = this._weightInterpolant;
  20811. if ( interpolant === null ) {
  20812. interpolant = mixer._lendControlInterpolant(),
  20813. this._weightInterpolant = interpolant;
  20814. }
  20815. var times = interpolant.parameterPositions,
  20816. values = interpolant.sampleValues;
  20817. times[ 0 ] = now; values[ 0 ] = weightNow;
  20818. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  20819. return this;
  20820. }
  20821. };
  20822. /**
  20823. *
  20824. * Player for AnimationClips.
  20825. *
  20826. *
  20827. * @author Ben Houston / http://clara.io/
  20828. * @author David Sarno / http://lighthaus.us/
  20829. * @author tschw
  20830. */
  20831. function AnimationMixer( root ) {
  20832. this._root = root;
  20833. this._initMemoryManager();
  20834. this._accuIndex = 0;
  20835. this.time = 0;
  20836. this.timeScale = 1.0;
  20837. }
  20838. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  20839. // return an action for a clip optionally using a custom root target
  20840. // object (this method allocates a lot of dynamic memory in case a
  20841. // previously unknown clip/root combination is specified)
  20842. clipAction: function( clip, optionalRoot ) {
  20843. var root = optionalRoot || this._root,
  20844. rootUuid = root.uuid,
  20845. clipObject = typeof clip === 'string' ?
  20846. AnimationClip.findByName( root, clip ) : clip,
  20847. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  20848. actionsForClip = this._actionsByClip[ clipUuid ],
  20849. prototypeAction = null;
  20850. if ( actionsForClip !== undefined ) {
  20851. var existingAction =
  20852. actionsForClip.actionByRoot[ rootUuid ];
  20853. if ( existingAction !== undefined ) {
  20854. return existingAction;
  20855. }
  20856. // we know the clip, so we don't have to parse all
  20857. // the bindings again but can just copy
  20858. prototypeAction = actionsForClip.knownActions[ 0 ];
  20859. // also, take the clip from the prototype action
  20860. if ( clipObject === null )
  20861. clipObject = prototypeAction._clip;
  20862. }
  20863. // clip must be known when specified via string
  20864. if ( clipObject === null ) return null;
  20865. // allocate all resources required to run it
  20866. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  20867. this._bindAction( newAction, prototypeAction );
  20868. // and make the action known to the memory manager
  20869. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20870. return newAction;
  20871. },
  20872. // get an existing action
  20873. existingAction: function( clip, optionalRoot ) {
  20874. var root = optionalRoot || this._root,
  20875. rootUuid = root.uuid,
  20876. clipObject = typeof clip === 'string' ?
  20877. AnimationClip.findByName( root, clip ) : clip,
  20878. clipUuid = clipObject ? clipObject.uuid : clip,
  20879. actionsForClip = this._actionsByClip[ clipUuid ];
  20880. if ( actionsForClip !== undefined ) {
  20881. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20882. }
  20883. return null;
  20884. },
  20885. // deactivates all previously scheduled actions
  20886. stopAllAction: function() {
  20887. var actions = this._actions,
  20888. nActions = this._nActiveActions,
  20889. bindings = this._bindings,
  20890. nBindings = this._nActiveBindings;
  20891. this._nActiveActions = 0;
  20892. this._nActiveBindings = 0;
  20893. for ( var i = 0; i !== nActions; ++ i ) {
  20894. actions[ i ].reset();
  20895. }
  20896. for ( var i = 0; i !== nBindings; ++ i ) {
  20897. bindings[ i ].useCount = 0;
  20898. }
  20899. return this;
  20900. },
  20901. // advance the time and update apply the animation
  20902. update: function( deltaTime ) {
  20903. deltaTime *= this.timeScale;
  20904. var actions = this._actions,
  20905. nActions = this._nActiveActions,
  20906. time = this.time += deltaTime,
  20907. timeDirection = Math.sign( deltaTime ),
  20908. accuIndex = this._accuIndex ^= 1;
  20909. // run active actions
  20910. for ( var i = 0; i !== nActions; ++ i ) {
  20911. var action = actions[ i ];
  20912. if ( action.enabled ) {
  20913. action._update( time, deltaTime, timeDirection, accuIndex );
  20914. }
  20915. }
  20916. // update scene graph
  20917. var bindings = this._bindings,
  20918. nBindings = this._nActiveBindings;
  20919. for ( var i = 0; i !== nBindings; ++ i ) {
  20920. bindings[ i ].apply( accuIndex );
  20921. }
  20922. return this;
  20923. },
  20924. // return this mixer's root target object
  20925. getRoot: function() {
  20926. return this._root;
  20927. },
  20928. // free all resources specific to a particular clip
  20929. uncacheClip: function( clip ) {
  20930. var actions = this._actions,
  20931. clipUuid = clip.uuid,
  20932. actionsByClip = this._actionsByClip,
  20933. actionsForClip = actionsByClip[ clipUuid ];
  20934. if ( actionsForClip !== undefined ) {
  20935. // note: just calling _removeInactiveAction would mess up the
  20936. // iteration state and also require updating the state we can
  20937. // just throw away
  20938. var actionsToRemove = actionsForClip.knownActions;
  20939. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20940. var action = actionsToRemove[ i ];
  20941. this._deactivateAction( action );
  20942. var cacheIndex = action._cacheIndex,
  20943. lastInactiveAction = actions[ actions.length - 1 ];
  20944. action._cacheIndex = null;
  20945. action._byClipCacheIndex = null;
  20946. lastInactiveAction._cacheIndex = cacheIndex;
  20947. actions[ cacheIndex ] = lastInactiveAction;
  20948. actions.pop();
  20949. this._removeInactiveBindingsForAction( action );
  20950. }
  20951. delete actionsByClip[ clipUuid ];
  20952. }
  20953. },
  20954. // free all resources specific to a particular root target object
  20955. uncacheRoot: function( root ) {
  20956. var rootUuid = root.uuid,
  20957. actionsByClip = this._actionsByClip;
  20958. for ( var clipUuid in actionsByClip ) {
  20959. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20960. action = actionByRoot[ rootUuid ];
  20961. if ( action !== undefined ) {
  20962. this._deactivateAction( action );
  20963. this._removeInactiveAction( action );
  20964. }
  20965. }
  20966. var bindingsByRoot = this._bindingsByRootAndName,
  20967. bindingByName = bindingsByRoot[ rootUuid ];
  20968. if ( bindingByName !== undefined ) {
  20969. for ( var trackName in bindingByName ) {
  20970. var binding = bindingByName[ trackName ];
  20971. binding.restoreOriginalState();
  20972. this._removeInactiveBinding( binding );
  20973. }
  20974. }
  20975. },
  20976. // remove a targeted clip from the cache
  20977. uncacheAction: function( clip, optionalRoot ) {
  20978. var action = this.existingAction( clip, optionalRoot );
  20979. if ( action !== null ) {
  20980. this._deactivateAction( action );
  20981. this._removeInactiveAction( action );
  20982. }
  20983. }
  20984. } );
  20985. // Implementation details:
  20986. Object.assign( AnimationMixer.prototype, {
  20987. _bindAction: function( action, prototypeAction ) {
  20988. var root = action._localRoot || this._root,
  20989. tracks = action._clip.tracks,
  20990. nTracks = tracks.length,
  20991. bindings = action._propertyBindings,
  20992. interpolants = action._interpolants,
  20993. rootUuid = root.uuid,
  20994. bindingsByRoot = this._bindingsByRootAndName,
  20995. bindingsByName = bindingsByRoot[ rootUuid ];
  20996. if ( bindingsByName === undefined ) {
  20997. bindingsByName = {};
  20998. bindingsByRoot[ rootUuid ] = bindingsByName;
  20999. }
  21000. for ( var i = 0; i !== nTracks; ++ i ) {
  21001. var track = tracks[ i ],
  21002. trackName = track.name,
  21003. binding = bindingsByName[ trackName ];
  21004. if ( binding !== undefined ) {
  21005. bindings[ i ] = binding;
  21006. } else {
  21007. binding = bindings[ i ];
  21008. if ( binding !== undefined ) {
  21009. // existing binding, make sure the cache knows
  21010. if ( binding._cacheIndex === null ) {
  21011. ++ binding.referenceCount;
  21012. this._addInactiveBinding( binding, rootUuid, trackName );
  21013. }
  21014. continue;
  21015. }
  21016. var path = prototypeAction && prototypeAction.
  21017. _propertyBindings[ i ].binding.parsedPath;
  21018. binding = new PropertyMixer(
  21019. PropertyBinding.create( root, trackName, path ),
  21020. track.ValueTypeName, track.getValueSize() );
  21021. ++ binding.referenceCount;
  21022. this._addInactiveBinding( binding, rootUuid, trackName );
  21023. bindings[ i ] = binding;
  21024. }
  21025. interpolants[ i ].resultBuffer = binding.buffer;
  21026. }
  21027. },
  21028. _activateAction: function( action ) {
  21029. if ( ! this._isActiveAction( action ) ) {
  21030. if ( action._cacheIndex === null ) {
  21031. // this action has been forgotten by the cache, but the user
  21032. // appears to be still using it -> rebind
  21033. var rootUuid = ( action._localRoot || this._root ).uuid,
  21034. clipUuid = action._clip.uuid,
  21035. actionsForClip = this._actionsByClip[ clipUuid ];
  21036. this._bindAction( action,
  21037. actionsForClip && actionsForClip.knownActions[ 0 ] );
  21038. this._addInactiveAction( action, clipUuid, rootUuid );
  21039. }
  21040. var bindings = action._propertyBindings;
  21041. // increment reference counts / sort out state
  21042. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21043. var binding = bindings[ i ];
  21044. if ( binding.useCount ++ === 0 ) {
  21045. this._lendBinding( binding );
  21046. binding.saveOriginalState();
  21047. }
  21048. }
  21049. this._lendAction( action );
  21050. }
  21051. },
  21052. _deactivateAction: function( action ) {
  21053. if ( this._isActiveAction( action ) ) {
  21054. var bindings = action._propertyBindings;
  21055. // decrement reference counts / sort out state
  21056. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21057. var binding = bindings[ i ];
  21058. if ( -- binding.useCount === 0 ) {
  21059. binding.restoreOriginalState();
  21060. this._takeBackBinding( binding );
  21061. }
  21062. }
  21063. this._takeBackAction( action );
  21064. }
  21065. },
  21066. // Memory manager
  21067. _initMemoryManager: function() {
  21068. this._actions = []; // 'nActiveActions' followed by inactive ones
  21069. this._nActiveActions = 0;
  21070. this._actionsByClip = {};
  21071. // inside:
  21072. // {
  21073. // knownActions: Array< AnimationAction > - used as prototypes
  21074. // actionByRoot: AnimationAction - lookup
  21075. // }
  21076. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  21077. this._nActiveBindings = 0;
  21078. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  21079. this._controlInterpolants = []; // same game as above
  21080. this._nActiveControlInterpolants = 0;
  21081. var scope = this;
  21082. this.stats = {
  21083. actions: {
  21084. get total() { return scope._actions.length; },
  21085. get inUse() { return scope._nActiveActions; }
  21086. },
  21087. bindings: {
  21088. get total() { return scope._bindings.length; },
  21089. get inUse() { return scope._nActiveBindings; }
  21090. },
  21091. controlInterpolants: {
  21092. get total() { return scope._controlInterpolants.length; },
  21093. get inUse() { return scope._nActiveControlInterpolants; }
  21094. }
  21095. };
  21096. },
  21097. // Memory management for AnimationAction objects
  21098. _isActiveAction: function( action ) {
  21099. var index = action._cacheIndex;
  21100. return index !== null && index < this._nActiveActions;
  21101. },
  21102. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  21103. var actions = this._actions,
  21104. actionsByClip = this._actionsByClip,
  21105. actionsForClip = actionsByClip[ clipUuid ];
  21106. if ( actionsForClip === undefined ) {
  21107. actionsForClip = {
  21108. knownActions: [ action ],
  21109. actionByRoot: {}
  21110. };
  21111. action._byClipCacheIndex = 0;
  21112. actionsByClip[ clipUuid ] = actionsForClip;
  21113. } else {
  21114. var knownActions = actionsForClip.knownActions;
  21115. action._byClipCacheIndex = knownActions.length;
  21116. knownActions.push( action );
  21117. }
  21118. action._cacheIndex = actions.length;
  21119. actions.push( action );
  21120. actionsForClip.actionByRoot[ rootUuid ] = action;
  21121. },
  21122. _removeInactiveAction: function( action ) {
  21123. var actions = this._actions,
  21124. lastInactiveAction = actions[ actions.length - 1 ],
  21125. cacheIndex = action._cacheIndex;
  21126. lastInactiveAction._cacheIndex = cacheIndex;
  21127. actions[ cacheIndex ] = lastInactiveAction;
  21128. actions.pop();
  21129. action._cacheIndex = null;
  21130. var clipUuid = action._clip.uuid,
  21131. actionsByClip = this._actionsByClip,
  21132. actionsForClip = actionsByClip[ clipUuid ],
  21133. knownActionsForClip = actionsForClip.knownActions,
  21134. lastKnownAction =
  21135. knownActionsForClip[ knownActionsForClip.length - 1 ],
  21136. byClipCacheIndex = action._byClipCacheIndex;
  21137. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  21138. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  21139. knownActionsForClip.pop();
  21140. action._byClipCacheIndex = null;
  21141. var actionByRoot = actionsForClip.actionByRoot,
  21142. rootUuid = ( actions._localRoot || this._root ).uuid;
  21143. delete actionByRoot[ rootUuid ];
  21144. if ( knownActionsForClip.length === 0 ) {
  21145. delete actionsByClip[ clipUuid ];
  21146. }
  21147. this._removeInactiveBindingsForAction( action );
  21148. },
  21149. _removeInactiveBindingsForAction: function( action ) {
  21150. var bindings = action._propertyBindings;
  21151. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21152. var binding = bindings[ i ];
  21153. if ( -- binding.referenceCount === 0 ) {
  21154. this._removeInactiveBinding( binding );
  21155. }
  21156. }
  21157. },
  21158. _lendAction: function( action ) {
  21159. // [ active actions | inactive actions ]
  21160. // [ active actions >| inactive actions ]
  21161. // s a
  21162. // <-swap->
  21163. // a s
  21164. var actions = this._actions,
  21165. prevIndex = action._cacheIndex,
  21166. lastActiveIndex = this._nActiveActions ++,
  21167. firstInactiveAction = actions[ lastActiveIndex ];
  21168. action._cacheIndex = lastActiveIndex;
  21169. actions[ lastActiveIndex ] = action;
  21170. firstInactiveAction._cacheIndex = prevIndex;
  21171. actions[ prevIndex ] = firstInactiveAction;
  21172. },
  21173. _takeBackAction: function( action ) {
  21174. // [ active actions | inactive actions ]
  21175. // [ active actions |< inactive actions ]
  21176. // a s
  21177. // <-swap->
  21178. // s a
  21179. var actions = this._actions,
  21180. prevIndex = action._cacheIndex,
  21181. firstInactiveIndex = -- this._nActiveActions,
  21182. lastActiveAction = actions[ firstInactiveIndex ];
  21183. action._cacheIndex = firstInactiveIndex;
  21184. actions[ firstInactiveIndex ] = action;
  21185. lastActiveAction._cacheIndex = prevIndex;
  21186. actions[ prevIndex ] = lastActiveAction;
  21187. },
  21188. // Memory management for PropertyMixer objects
  21189. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  21190. var bindingsByRoot = this._bindingsByRootAndName,
  21191. bindingByName = bindingsByRoot[ rootUuid ],
  21192. bindings = this._bindings;
  21193. if ( bindingByName === undefined ) {
  21194. bindingByName = {};
  21195. bindingsByRoot[ rootUuid ] = bindingByName;
  21196. }
  21197. bindingByName[ trackName ] = binding;
  21198. binding._cacheIndex = bindings.length;
  21199. bindings.push( binding );
  21200. },
  21201. _removeInactiveBinding: function( binding ) {
  21202. var bindings = this._bindings,
  21203. propBinding = binding.binding,
  21204. rootUuid = propBinding.rootNode.uuid,
  21205. trackName = propBinding.path,
  21206. bindingsByRoot = this._bindingsByRootAndName,
  21207. bindingByName = bindingsByRoot[ rootUuid ],
  21208. lastInactiveBinding = bindings[ bindings.length - 1 ],
  21209. cacheIndex = binding._cacheIndex;
  21210. lastInactiveBinding._cacheIndex = cacheIndex;
  21211. bindings[ cacheIndex ] = lastInactiveBinding;
  21212. bindings.pop();
  21213. delete bindingByName[ trackName ];
  21214. remove_empty_map: {
  21215. for ( var _ in bindingByName ) break remove_empty_map;
  21216. delete bindingsByRoot[ rootUuid ];
  21217. }
  21218. },
  21219. _lendBinding: function( binding ) {
  21220. var bindings = this._bindings,
  21221. prevIndex = binding._cacheIndex,
  21222. lastActiveIndex = this._nActiveBindings ++,
  21223. firstInactiveBinding = bindings[ lastActiveIndex ];
  21224. binding._cacheIndex = lastActiveIndex;
  21225. bindings[ lastActiveIndex ] = binding;
  21226. firstInactiveBinding._cacheIndex = prevIndex;
  21227. bindings[ prevIndex ] = firstInactiveBinding;
  21228. },
  21229. _takeBackBinding: function( binding ) {
  21230. var bindings = this._bindings,
  21231. prevIndex = binding._cacheIndex,
  21232. firstInactiveIndex = -- this._nActiveBindings,
  21233. lastActiveBinding = bindings[ firstInactiveIndex ];
  21234. binding._cacheIndex = firstInactiveIndex;
  21235. bindings[ firstInactiveIndex ] = binding;
  21236. lastActiveBinding._cacheIndex = prevIndex;
  21237. bindings[ prevIndex ] = lastActiveBinding;
  21238. },
  21239. // Memory management of Interpolants for weight and time scale
  21240. _lendControlInterpolant: function() {
  21241. var interpolants = this._controlInterpolants,
  21242. lastActiveIndex = this._nActiveControlInterpolants ++,
  21243. interpolant = interpolants[ lastActiveIndex ];
  21244. if ( interpolant === undefined ) {
  21245. interpolant = new LinearInterpolant(
  21246. new Float32Array( 2 ), new Float32Array( 2 ),
  21247. 1, this._controlInterpolantsResultBuffer );
  21248. interpolant.__cacheIndex = lastActiveIndex;
  21249. interpolants[ lastActiveIndex ] = interpolant;
  21250. }
  21251. return interpolant;
  21252. },
  21253. _takeBackControlInterpolant: function( interpolant ) {
  21254. var interpolants = this._controlInterpolants,
  21255. prevIndex = interpolant.__cacheIndex,
  21256. firstInactiveIndex = -- this._nActiveControlInterpolants,
  21257. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  21258. interpolant.__cacheIndex = firstInactiveIndex;
  21259. interpolants[ firstInactiveIndex ] = interpolant;
  21260. lastActiveInterpolant.__cacheIndex = prevIndex;
  21261. interpolants[ prevIndex ] = lastActiveInterpolant;
  21262. },
  21263. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  21264. } );
  21265. /**
  21266. * @author mrdoob / http://mrdoob.com/
  21267. */
  21268. function Uniform( value ) {
  21269. if ( typeof value === 'string' ) {
  21270. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  21271. value = arguments[ 1 ];
  21272. }
  21273. this.value = value;
  21274. this.dynamic = false;
  21275. }
  21276. Uniform.prototype = {
  21277. constructor: Uniform,
  21278. onUpdate: function ( callback ) {
  21279. this.dynamic = true;
  21280. this.onUpdateCallback = callback;
  21281. return this;
  21282. }
  21283. };
  21284. /**
  21285. * @author benaadams / https://twitter.com/ben_a_adams
  21286. */
  21287. function InstancedBufferGeometry() {
  21288. BufferGeometry.call( this );
  21289. this.type = 'InstancedBufferGeometry';
  21290. this.maxInstancedCount = undefined;
  21291. }
  21292. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21293. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  21294. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  21295. InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  21296. this.groups.push( {
  21297. start: start,
  21298. count: count,
  21299. instances: instances
  21300. } );
  21301. };
  21302. InstancedBufferGeometry.prototype.copy = function ( source ) {
  21303. var index = source.index;
  21304. if ( index !== null ) {
  21305. this.setIndex( index.clone() );
  21306. }
  21307. var attributes = source.attributes;
  21308. for ( var name in attributes ) {
  21309. var attribute = attributes[ name ];
  21310. this.addAttribute( name, attribute.clone() );
  21311. }
  21312. var groups = source.groups;
  21313. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  21314. var group = groups[ i ];
  21315. this.addGroup( group.start, group.count, group.instances );
  21316. }
  21317. return this;
  21318. };
  21319. /**
  21320. * @author benaadams / https://twitter.com/ben_a_adams
  21321. */
  21322. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21323. this.uuid = exports.Math.generateUUID();
  21324. this.data = interleavedBuffer;
  21325. this.itemSize = itemSize;
  21326. this.offset = offset;
  21327. this.normalized = normalized === true;
  21328. }
  21329. InterleavedBufferAttribute.prototype = {
  21330. constructor: InterleavedBufferAttribute,
  21331. isInterleavedBufferAttribute: true,
  21332. get length() {
  21333. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  21334. return this.array.length;
  21335. },
  21336. get count() {
  21337. return this.data.count;
  21338. },
  21339. get array() {
  21340. return this.data.array;
  21341. },
  21342. setX: function ( index, x ) {
  21343. this.data.array[ index * this.data.stride + this.offset ] = x;
  21344. return this;
  21345. },
  21346. setY: function ( index, y ) {
  21347. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21348. return this;
  21349. },
  21350. setZ: function ( index, z ) {
  21351. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21352. return this;
  21353. },
  21354. setW: function ( index, w ) {
  21355. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21356. return this;
  21357. },
  21358. getX: function ( index ) {
  21359. return this.data.array[ index * this.data.stride + this.offset ];
  21360. },
  21361. getY: function ( index ) {
  21362. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21363. },
  21364. getZ: function ( index ) {
  21365. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21366. },
  21367. getW: function ( index ) {
  21368. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21369. },
  21370. setXY: function ( index, x, y ) {
  21371. index = index * this.data.stride + this.offset;
  21372. this.data.array[ index + 0 ] = x;
  21373. this.data.array[ index + 1 ] = y;
  21374. return this;
  21375. },
  21376. setXYZ: function ( index, x, y, z ) {
  21377. index = index * this.data.stride + this.offset;
  21378. this.data.array[ index + 0 ] = x;
  21379. this.data.array[ index + 1 ] = y;
  21380. this.data.array[ index + 2 ] = z;
  21381. return this;
  21382. },
  21383. setXYZW: function ( index, x, y, z, w ) {
  21384. index = index * this.data.stride + this.offset;
  21385. this.data.array[ index + 0 ] = x;
  21386. this.data.array[ index + 1 ] = y;
  21387. this.data.array[ index + 2 ] = z;
  21388. this.data.array[ index + 3 ] = w;
  21389. return this;
  21390. }
  21391. };
  21392. /**
  21393. * @author benaadams / https://twitter.com/ben_a_adams
  21394. */
  21395. function InterleavedBuffer( array, stride ) {
  21396. this.uuid = exports.Math.generateUUID();
  21397. this.array = array;
  21398. this.stride = stride;
  21399. this.dynamic = false;
  21400. this.updateRange = { offset: 0, count: - 1 };
  21401. this.version = 0;
  21402. }
  21403. InterleavedBuffer.prototype = {
  21404. constructor: InterleavedBuffer,
  21405. isInterleavedBuffer: true,
  21406. get length () {
  21407. return this.array.length;
  21408. },
  21409. get count () {
  21410. return this.array.length / this.stride;
  21411. },
  21412. set needsUpdate( value ) {
  21413. if ( value === true ) this.version ++;
  21414. },
  21415. setDynamic: function ( value ) {
  21416. this.dynamic = value;
  21417. return this;
  21418. },
  21419. copy: function ( source ) {
  21420. this.array = new source.array.constructor( source.array );
  21421. this.stride = source.stride;
  21422. this.dynamic = source.dynamic;
  21423. return this;
  21424. },
  21425. copyAt: function ( index1, attribute, index2 ) {
  21426. index1 *= this.stride;
  21427. index2 *= attribute.stride;
  21428. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21429. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21430. }
  21431. return this;
  21432. },
  21433. set: function ( value, offset ) {
  21434. if ( offset === undefined ) offset = 0;
  21435. this.array.set( value, offset );
  21436. return this;
  21437. },
  21438. clone: function () {
  21439. return new this.constructor().copy( this );
  21440. }
  21441. };
  21442. /**
  21443. * @author benaadams / https://twitter.com/ben_a_adams
  21444. */
  21445. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  21446. InterleavedBuffer.call( this, array, stride );
  21447. this.meshPerAttribute = meshPerAttribute || 1;
  21448. }
  21449. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  21450. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  21451. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  21452. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  21453. InterleavedBuffer.prototype.copy.call( this, source );
  21454. this.meshPerAttribute = source.meshPerAttribute;
  21455. return this;
  21456. };
  21457. /**
  21458. * @author benaadams / https://twitter.com/ben_a_adams
  21459. */
  21460. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  21461. BufferAttribute.call( this, array, itemSize );
  21462. this.meshPerAttribute = meshPerAttribute || 1;
  21463. }
  21464. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  21465. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  21466. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  21467. InstancedBufferAttribute.prototype.copy = function ( source ) {
  21468. BufferAttribute.prototype.copy.call( this, source );
  21469. this.meshPerAttribute = source.meshPerAttribute;
  21470. return this;
  21471. };
  21472. /**
  21473. * @author mrdoob / http://mrdoob.com/
  21474. * @author bhouston / http://clara.io/
  21475. * @author stephomi / http://stephaneginier.com/
  21476. */
  21477. function Raycaster( origin, direction, near, far ) {
  21478. this.ray = new Ray( origin, direction );
  21479. // direction is assumed to be normalized (for accurate distance calculations)
  21480. this.near = near || 0;
  21481. this.far = far || Infinity;
  21482. this.params = {
  21483. Mesh: {},
  21484. Line: {},
  21485. LOD: {},
  21486. Points: { threshold: 1 },
  21487. Sprite: {}
  21488. };
  21489. Object.defineProperties( this.params, {
  21490. PointCloud: {
  21491. get: function () {
  21492. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  21493. return this.Points;
  21494. }
  21495. }
  21496. } );
  21497. }
  21498. function ascSort( a, b ) {
  21499. return a.distance - b.distance;
  21500. }
  21501. function intersectObject( object, raycaster, intersects, recursive ) {
  21502. if ( object.visible === false ) return;
  21503. object.raycast( raycaster, intersects );
  21504. if ( recursive === true ) {
  21505. var children = object.children;
  21506. for ( var i = 0, l = children.length; i < l; i ++ ) {
  21507. intersectObject( children[ i ], raycaster, intersects, true );
  21508. }
  21509. }
  21510. }
  21511. //
  21512. Raycaster.prototype = {
  21513. constructor: Raycaster,
  21514. linePrecision: 1,
  21515. set: function ( origin, direction ) {
  21516. // direction is assumed to be normalized (for accurate distance calculations)
  21517. this.ray.set( origin, direction );
  21518. },
  21519. setFromCamera: function ( coords, camera ) {
  21520. if ( (camera && camera.isPerspectiveCamera) ) {
  21521. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  21522. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  21523. } else if ( (camera && camera.isOrthographicCamera) ) {
  21524. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  21525. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  21526. } else {
  21527. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  21528. }
  21529. },
  21530. intersectObject: function ( object, recursive ) {
  21531. var intersects = [];
  21532. intersectObject( object, this, intersects, recursive );
  21533. intersects.sort( ascSort );
  21534. return intersects;
  21535. },
  21536. intersectObjects: function ( objects, recursive ) {
  21537. var intersects = [];
  21538. if ( Array.isArray( objects ) === false ) {
  21539. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  21540. return intersects;
  21541. }
  21542. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  21543. intersectObject( objects[ i ], this, intersects, recursive );
  21544. }
  21545. intersects.sort( ascSort );
  21546. return intersects;
  21547. }
  21548. };
  21549. /**
  21550. * @author alteredq / http://alteredqualia.com/
  21551. */
  21552. function Clock( autoStart ) {
  21553. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  21554. this.startTime = 0;
  21555. this.oldTime = 0;
  21556. this.elapsedTime = 0;
  21557. this.running = false;
  21558. }
  21559. Clock.prototype = {
  21560. constructor: Clock,
  21561. start: function () {
  21562. this.startTime = ( performance || Date ).now();
  21563. this.oldTime = this.startTime;
  21564. this.running = true;
  21565. },
  21566. stop: function () {
  21567. this.getElapsedTime();
  21568. this.running = false;
  21569. },
  21570. getElapsedTime: function () {
  21571. this.getDelta();
  21572. return this.elapsedTime;
  21573. },
  21574. getDelta: function () {
  21575. var diff = 0;
  21576. if ( this.autoStart && ! this.running ) {
  21577. this.start();
  21578. }
  21579. if ( this.running ) {
  21580. var newTime = ( performance || Date ).now();
  21581. diff = ( newTime - this.oldTime ) / 1000;
  21582. this.oldTime = newTime;
  21583. this.elapsedTime += diff;
  21584. }
  21585. return diff;
  21586. }
  21587. };
  21588. /**
  21589. * Spline from Tween.js, slightly optimized (and trashed)
  21590. * http://sole.github.com/tween.js/examples/05_spline.html
  21591. *
  21592. * @author mrdoob / http://mrdoob.com/
  21593. * @author alteredq / http://alteredqualia.com/
  21594. */
  21595. function Spline( points ) {
  21596. this.points = points;
  21597. var c = [], v3 = { x: 0, y: 0, z: 0 },
  21598. point, intPoint, weight, w2, w3,
  21599. pa, pb, pc, pd;
  21600. this.initFromArray = function ( a ) {
  21601. this.points = [];
  21602. for ( var i = 0; i < a.length; i ++ ) {
  21603. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  21604. }
  21605. };
  21606. this.getPoint = function ( k ) {
  21607. point = ( this.points.length - 1 ) * k;
  21608. intPoint = Math.floor( point );
  21609. weight = point - intPoint;
  21610. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  21611. c[ 1 ] = intPoint;
  21612. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  21613. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  21614. pa = this.points[ c[ 0 ] ];
  21615. pb = this.points[ c[ 1 ] ];
  21616. pc = this.points[ c[ 2 ] ];
  21617. pd = this.points[ c[ 3 ] ];
  21618. w2 = weight * weight;
  21619. w3 = weight * w2;
  21620. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  21621. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  21622. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  21623. return v3;
  21624. };
  21625. this.getControlPointsArray = function () {
  21626. var i, p, l = this.points.length,
  21627. coords = [];
  21628. for ( i = 0; i < l; i ++ ) {
  21629. p = this.points[ i ];
  21630. coords[ i ] = [ p.x, p.y, p.z ];
  21631. }
  21632. return coords;
  21633. };
  21634. // approximate length by summing linear segments
  21635. this.getLength = function ( nSubDivisions ) {
  21636. var i, index, nSamples, position,
  21637. point = 0, intPoint = 0, oldIntPoint = 0,
  21638. oldPosition = new Vector3(),
  21639. tmpVec = new Vector3(),
  21640. chunkLengths = [],
  21641. totalLength = 0;
  21642. // first point has 0 length
  21643. chunkLengths[ 0 ] = 0;
  21644. if ( ! nSubDivisions ) nSubDivisions = 100;
  21645. nSamples = this.points.length * nSubDivisions;
  21646. oldPosition.copy( this.points[ 0 ] );
  21647. for ( i = 1; i < nSamples; i ++ ) {
  21648. index = i / nSamples;
  21649. position = this.getPoint( index );
  21650. tmpVec.copy( position );
  21651. totalLength += tmpVec.distanceTo( oldPosition );
  21652. oldPosition.copy( position );
  21653. point = ( this.points.length - 1 ) * index;
  21654. intPoint = Math.floor( point );
  21655. if ( intPoint !== oldIntPoint ) {
  21656. chunkLengths[ intPoint ] = totalLength;
  21657. oldIntPoint = intPoint;
  21658. }
  21659. }
  21660. // last point ends with total length
  21661. chunkLengths[ chunkLengths.length ] = totalLength;
  21662. return { chunks: chunkLengths, total: totalLength };
  21663. };
  21664. this.reparametrizeByArcLength = function ( samplingCoef ) {
  21665. var i, j,
  21666. index, indexCurrent, indexNext,
  21667. realDistance,
  21668. sampling, position,
  21669. newpoints = [],
  21670. tmpVec = new Vector3(),
  21671. sl = this.getLength();
  21672. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  21673. for ( i = 1; i < this.points.length; i ++ ) {
  21674. //tmpVec.copy( this.points[ i - 1 ] );
  21675. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  21676. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  21677. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  21678. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  21679. indexNext = i / ( this.points.length - 1 );
  21680. for ( j = 1; j < sampling - 1; j ++ ) {
  21681. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  21682. position = this.getPoint( index );
  21683. newpoints.push( tmpVec.copy( position ).clone() );
  21684. }
  21685. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  21686. }
  21687. this.points = newpoints;
  21688. };
  21689. // Catmull-Rom
  21690. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  21691. var v0 = ( p2 - p0 ) * 0.5,
  21692. v1 = ( p3 - p1 ) * 0.5;
  21693. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21694. }
  21695. }
  21696. /**
  21697. * @author bhouston / http://clara.io
  21698. * @author WestLangley / http://github.com/WestLangley
  21699. *
  21700. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  21701. *
  21702. * The poles (phi) are at the positive and negative y axis.
  21703. * The equator starts at positive z.
  21704. */
  21705. function Spherical( radius, phi, theta ) {
  21706. this.radius = ( radius !== undefined ) ? radius : 1.0;
  21707. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  21708. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  21709. return this;
  21710. }
  21711. Spherical.prototype = {
  21712. constructor: Spherical,
  21713. set: function ( radius, phi, theta ) {
  21714. this.radius = radius;
  21715. this.phi = phi;
  21716. this.theta = theta;
  21717. return this;
  21718. },
  21719. clone: function () {
  21720. return new this.constructor().copy( this );
  21721. },
  21722. copy: function ( other ) {
  21723. this.radius.copy( other.radius );
  21724. this.phi.copy( other.phi );
  21725. this.theta.copy( other.theta );
  21726. return this;
  21727. },
  21728. // restrict phi to be betwee EPS and PI-EPS
  21729. makeSafe: function() {
  21730. var EPS = 0.000001;
  21731. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  21732. return this;
  21733. },
  21734. setFromVector3: function( vec3 ) {
  21735. this.radius = vec3.length();
  21736. if ( this.radius === 0 ) {
  21737. this.theta = 0;
  21738. this.phi = 0;
  21739. } else {
  21740. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  21741. this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  21742. }
  21743. return this;
  21744. },
  21745. };
  21746. /**
  21747. * @author alteredq / http://alteredqualia.com/
  21748. */
  21749. function MorphBlendMesh( geometry, material ) {
  21750. Mesh.call( this, geometry, material );
  21751. this.animationsMap = {};
  21752. this.animationsList = [];
  21753. // prepare default animation
  21754. // (all frames played together in 1 second)
  21755. var numFrames = this.geometry.morphTargets.length;
  21756. var name = "__default";
  21757. var startFrame = 0;
  21758. var endFrame = numFrames - 1;
  21759. var fps = numFrames / 1;
  21760. this.createAnimation( name, startFrame, endFrame, fps );
  21761. this.setAnimationWeight( name, 1 );
  21762. }
  21763. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  21764. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  21765. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21766. var animation = {
  21767. start: start,
  21768. end: end,
  21769. length: end - start + 1,
  21770. fps: fps,
  21771. duration: ( end - start ) / fps,
  21772. lastFrame: 0,
  21773. currentFrame: 0,
  21774. active: false,
  21775. time: 0,
  21776. direction: 1,
  21777. weight: 1,
  21778. directionBackwards: false,
  21779. mirroredLoop: false
  21780. };
  21781. this.animationsMap[ name ] = animation;
  21782. this.animationsList.push( animation );
  21783. };
  21784. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21785. var pattern = /([a-z]+)_?(\d+)/i;
  21786. var firstAnimation, frameRanges = {};
  21787. var geometry = this.geometry;
  21788. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21789. var morph = geometry.morphTargets[ i ];
  21790. var chunks = morph.name.match( pattern );
  21791. if ( chunks && chunks.length > 1 ) {
  21792. var name = chunks[ 1 ];
  21793. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21794. var range = frameRanges[ name ];
  21795. if ( i < range.start ) range.start = i;
  21796. if ( i > range.end ) range.end = i;
  21797. if ( ! firstAnimation ) firstAnimation = name;
  21798. }
  21799. }
  21800. for ( var name in frameRanges ) {
  21801. var range = frameRanges[ name ];
  21802. this.createAnimation( name, range.start, range.end, fps );
  21803. }
  21804. this.firstAnimation = firstAnimation;
  21805. };
  21806. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21807. var animation = this.animationsMap[ name ];
  21808. if ( animation ) {
  21809. animation.direction = 1;
  21810. animation.directionBackwards = false;
  21811. }
  21812. };
  21813. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21814. var animation = this.animationsMap[ name ];
  21815. if ( animation ) {
  21816. animation.direction = - 1;
  21817. animation.directionBackwards = true;
  21818. }
  21819. };
  21820. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21821. var animation = this.animationsMap[ name ];
  21822. if ( animation ) {
  21823. animation.fps = fps;
  21824. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21825. }
  21826. };
  21827. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21828. var animation = this.animationsMap[ name ];
  21829. if ( animation ) {
  21830. animation.duration = duration;
  21831. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21832. }
  21833. };
  21834. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21835. var animation = this.animationsMap[ name ];
  21836. if ( animation ) {
  21837. animation.weight = weight;
  21838. }
  21839. };
  21840. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21841. var animation = this.animationsMap[ name ];
  21842. if ( animation ) {
  21843. animation.time = time;
  21844. }
  21845. };
  21846. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21847. var time = 0;
  21848. var animation = this.animationsMap[ name ];
  21849. if ( animation ) {
  21850. time = animation.time;
  21851. }
  21852. return time;
  21853. };
  21854. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21855. var duration = - 1;
  21856. var animation = this.animationsMap[ name ];
  21857. if ( animation ) {
  21858. duration = animation.duration;
  21859. }
  21860. return duration;
  21861. };
  21862. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21863. var animation = this.animationsMap[ name ];
  21864. if ( animation ) {
  21865. animation.time = 0;
  21866. animation.active = true;
  21867. } else {
  21868. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21869. }
  21870. };
  21871. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21872. var animation = this.animationsMap[ name ];
  21873. if ( animation ) {
  21874. animation.active = false;
  21875. }
  21876. };
  21877. MorphBlendMesh.prototype.update = function ( delta ) {
  21878. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21879. var animation = this.animationsList[ i ];
  21880. if ( ! animation.active ) continue;
  21881. var frameTime = animation.duration / animation.length;
  21882. animation.time += animation.direction * delta;
  21883. if ( animation.mirroredLoop ) {
  21884. if ( animation.time > animation.duration || animation.time < 0 ) {
  21885. animation.direction *= - 1;
  21886. if ( animation.time > animation.duration ) {
  21887. animation.time = animation.duration;
  21888. animation.directionBackwards = true;
  21889. }
  21890. if ( animation.time < 0 ) {
  21891. animation.time = 0;
  21892. animation.directionBackwards = false;
  21893. }
  21894. }
  21895. } else {
  21896. animation.time = animation.time % animation.duration;
  21897. if ( animation.time < 0 ) animation.time += animation.duration;
  21898. }
  21899. var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21900. var weight = animation.weight;
  21901. if ( keyframe !== animation.currentFrame ) {
  21902. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21903. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21904. this.morphTargetInfluences[ keyframe ] = 0;
  21905. animation.lastFrame = animation.currentFrame;
  21906. animation.currentFrame = keyframe;
  21907. }
  21908. var mix = ( animation.time % frameTime ) / frameTime;
  21909. if ( animation.directionBackwards ) mix = 1 - mix;
  21910. if ( animation.currentFrame !== animation.lastFrame ) {
  21911. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21912. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21913. } else {
  21914. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  21915. }
  21916. }
  21917. };
  21918. /**
  21919. * @author alteredq / http://alteredqualia.com/
  21920. */
  21921. function ImmediateRenderObject( material ) {
  21922. Object3D.call( this );
  21923. this.material = material;
  21924. this.render = function ( renderCallback ) {};
  21925. }
  21926. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  21927. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  21928. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  21929. /**
  21930. * @author mrdoob / http://mrdoob.com/
  21931. */
  21932. function WireframeGeometry( geometry ) {
  21933. BufferGeometry.call( this );
  21934. var edge = [ 0, 0 ], hash = {};
  21935. function sortFunction( a, b ) {
  21936. return a - b;
  21937. }
  21938. var keys = [ 'a', 'b', 'c' ];
  21939. if ( (geometry && geometry.isGeometry) ) {
  21940. var vertices = geometry.vertices;
  21941. var faces = geometry.faces;
  21942. var numEdges = 0;
  21943. // allocate maximal size
  21944. var edges = new Uint32Array( 6 * faces.length );
  21945. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21946. var face = faces[ i ];
  21947. for ( var j = 0; j < 3; j ++ ) {
  21948. edge[ 0 ] = face[ keys[ j ] ];
  21949. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21950. edge.sort( sortFunction );
  21951. var key = edge.toString();
  21952. if ( hash[ key ] === undefined ) {
  21953. edges[ 2 * numEdges ] = edge[ 0 ];
  21954. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21955. hash[ key ] = true;
  21956. numEdges ++;
  21957. }
  21958. }
  21959. }
  21960. var coords = new Float32Array( numEdges * 2 * 3 );
  21961. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21962. for ( var j = 0; j < 2; j ++ ) {
  21963. var vertex = vertices[ edges [ 2 * i + j ] ];
  21964. var index = 6 * i + 3 * j;
  21965. coords[ index + 0 ] = vertex.x;
  21966. coords[ index + 1 ] = vertex.y;
  21967. coords[ index + 2 ] = vertex.z;
  21968. }
  21969. }
  21970. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  21971. } else if ( (geometry && geometry.isBufferGeometry) ) {
  21972. if ( geometry.index !== null ) {
  21973. // Indexed BufferGeometry
  21974. var indices = geometry.index.array;
  21975. var vertices = geometry.attributes.position;
  21976. var groups = geometry.groups;
  21977. var numEdges = 0;
  21978. if ( groups.length === 0 ) {
  21979. geometry.addGroup( 0, indices.length );
  21980. }
  21981. // allocate maximal size
  21982. var edges = new Uint32Array( 2 * indices.length );
  21983. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  21984. var group = groups[ o ];
  21985. var start = group.start;
  21986. var count = group.count;
  21987. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21988. for ( var j = 0; j < 3; j ++ ) {
  21989. edge[ 0 ] = indices[ i + j ];
  21990. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  21991. edge.sort( sortFunction );
  21992. var key = edge.toString();
  21993. if ( hash[ key ] === undefined ) {
  21994. edges[ 2 * numEdges ] = edge[ 0 ];
  21995. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21996. hash[ key ] = true;
  21997. numEdges ++;
  21998. }
  21999. }
  22000. }
  22001. }
  22002. var coords = new Float32Array( numEdges * 2 * 3 );
  22003. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22004. for ( var j = 0; j < 2; j ++ ) {
  22005. var index = 6 * i + 3 * j;
  22006. var index2 = edges[ 2 * i + j ];
  22007. coords[ index + 0 ] = vertices.getX( index2 );
  22008. coords[ index + 1 ] = vertices.getY( index2 );
  22009. coords[ index + 2 ] = vertices.getZ( index2 );
  22010. }
  22011. }
  22012. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  22013. } else {
  22014. // non-indexed BufferGeometry
  22015. var vertices = geometry.attributes.position.array;
  22016. var numEdges = vertices.length / 3;
  22017. var numTris = numEdges / 3;
  22018. var coords = new Float32Array( numEdges * 2 * 3 );
  22019. for ( var i = 0, l = numTris; i < l; i ++ ) {
  22020. for ( var j = 0; j < 3; j ++ ) {
  22021. var index = 18 * i + 6 * j;
  22022. var index1 = 9 * i + 3 * j;
  22023. coords[ index + 0 ] = vertices[ index1 ];
  22024. coords[ index + 1 ] = vertices[ index1 + 1 ];
  22025. coords[ index + 2 ] = vertices[ index1 + 2 ];
  22026. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  22027. coords[ index + 3 ] = vertices[ index2 ];
  22028. coords[ index + 4 ] = vertices[ index2 + 1 ];
  22029. coords[ index + 5 ] = vertices[ index2 + 2 ];
  22030. }
  22031. }
  22032. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  22033. }
  22034. }
  22035. }
  22036. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  22037. WireframeGeometry.prototype.constructor = WireframeGeometry;
  22038. /**
  22039. * @author mrdoob / http://mrdoob.com/
  22040. */
  22041. function WireframeHelper( object, hex ) {
  22042. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22043. LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) );
  22044. this.matrix = object.matrixWorld;
  22045. this.matrixAutoUpdate = false;
  22046. }
  22047. WireframeHelper.prototype = Object.create( LineSegments.prototype );
  22048. WireframeHelper.prototype.constructor = WireframeHelper;
  22049. /**
  22050. * @author mrdoob / http://mrdoob.com/
  22051. * @author WestLangley / http://github.com/WestLangley
  22052. */
  22053. function VertexNormalsHelper( object, size, hex, linewidth ) {
  22054. this.object = object;
  22055. this.size = ( size !== undefined ) ? size : 1;
  22056. var color = ( hex !== undefined ) ? hex : 0xff0000;
  22057. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22058. //
  22059. var nNormals = 0;
  22060. var objGeometry = this.object.geometry;
  22061. if ( (objGeometry && objGeometry.isGeometry) ) {
  22062. nNormals = objGeometry.faces.length * 3;
  22063. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  22064. nNormals = objGeometry.attributes.normal.count;
  22065. }
  22066. //
  22067. var geometry = new BufferGeometry();
  22068. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  22069. geometry.addAttribute( 'position', positions );
  22070. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22071. //
  22072. this.matrixAutoUpdate = false;
  22073. this.update();
  22074. }
  22075. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22076. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  22077. VertexNormalsHelper.prototype.update = ( function () {
  22078. var v1 = new Vector3();
  22079. var v2 = new Vector3();
  22080. var normalMatrix = new Matrix3();
  22081. return function update() {
  22082. var keys = [ 'a', 'b', 'c' ];
  22083. this.object.updateMatrixWorld( true );
  22084. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22085. var matrixWorld = this.object.matrixWorld;
  22086. var position = this.geometry.attributes.position;
  22087. //
  22088. var objGeometry = this.object.geometry;
  22089. if ( (objGeometry && objGeometry.isGeometry) ) {
  22090. var vertices = objGeometry.vertices;
  22091. var faces = objGeometry.faces;
  22092. var idx = 0;
  22093. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22094. var face = faces[ i ];
  22095. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  22096. var vertex = vertices[ face[ keys[ j ] ] ];
  22097. var normal = face.vertexNormals[ j ];
  22098. v1.copy( vertex ).applyMatrix4( matrixWorld );
  22099. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22100. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22101. idx = idx + 1;
  22102. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22103. idx = idx + 1;
  22104. }
  22105. }
  22106. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  22107. var objPos = objGeometry.attributes.position;
  22108. var objNorm = objGeometry.attributes.normal;
  22109. var idx = 0;
  22110. // for simplicity, ignore index and drawcalls, and render every normal
  22111. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  22112. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  22113. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  22114. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22115. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22116. idx = idx + 1;
  22117. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22118. idx = idx + 1;
  22119. }
  22120. }
  22121. position.needsUpdate = true;
  22122. return this;
  22123. };
  22124. }() );
  22125. /**
  22126. * @author alteredq / http://alteredqualia.com/
  22127. * @author mrdoob / http://mrdoob.com/
  22128. * @author WestLangley / http://github.com/WestLangley
  22129. */
  22130. function SpotLightHelper( light ) {
  22131. Object3D.call( this );
  22132. this.light = light;
  22133. this.light.updateMatrixWorld();
  22134. this.matrix = light.matrixWorld;
  22135. this.matrixAutoUpdate = false;
  22136. var geometry = new BufferGeometry();
  22137. var positions = [
  22138. 0, 0, 0, 0, 0, 1,
  22139. 0, 0, 0, 1, 0, 1,
  22140. 0, 0, 0, - 1, 0, 1,
  22141. 0, 0, 0, 0, 1, 1,
  22142. 0, 0, 0, 0, - 1, 1
  22143. ];
  22144. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  22145. var p1 = ( i / l ) * Math.PI * 2;
  22146. var p2 = ( j / l ) * Math.PI * 2;
  22147. positions.push(
  22148. Math.cos( p1 ), Math.sin( p1 ), 1,
  22149. Math.cos( p2 ), Math.sin( p2 ), 1
  22150. );
  22151. }
  22152. geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) );
  22153. var material = new LineBasicMaterial( { fog: false } );
  22154. this.cone = new LineSegments( geometry, material );
  22155. this.add( this.cone );
  22156. this.update();
  22157. }
  22158. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  22159. SpotLightHelper.prototype.constructor = SpotLightHelper;
  22160. SpotLightHelper.prototype.dispose = function () {
  22161. this.cone.geometry.dispose();
  22162. this.cone.material.dispose();
  22163. };
  22164. SpotLightHelper.prototype.update = function () {
  22165. var vector = new Vector3();
  22166. var vector2 = new Vector3();
  22167. return function update() {
  22168. var coneLength = this.light.distance ? this.light.distance : 1000;
  22169. var coneWidth = coneLength * Math.tan( this.light.angle );
  22170. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22171. vector.setFromMatrixPosition( this.light.matrixWorld );
  22172. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  22173. this.cone.lookAt( vector2.sub( vector ) );
  22174. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22175. };
  22176. }();
  22177. /**
  22178. * @author Sean Griffin / http://twitter.com/sgrif
  22179. * @author Michael Guerrero / http://realitymeltdown.com
  22180. * @author mrdoob / http://mrdoob.com/
  22181. * @author ikerr / http://verold.com
  22182. */
  22183. function SkeletonHelper( object ) {
  22184. this.bones = this.getBoneList( object );
  22185. var geometry = new Geometry();
  22186. for ( var i = 0; i < this.bones.length; i ++ ) {
  22187. var bone = this.bones[ i ];
  22188. if ( (bone.parent && bone.parent.isBone) ) {
  22189. geometry.vertices.push( new Vector3() );
  22190. geometry.vertices.push( new Vector3() );
  22191. geometry.colors.push( new Color( 0, 0, 1 ) );
  22192. geometry.colors.push( new Color( 0, 1, 0 ) );
  22193. }
  22194. }
  22195. geometry.dynamic = true;
  22196. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  22197. LineSegments.call( this, geometry, material );
  22198. this.root = object;
  22199. this.matrix = object.matrixWorld;
  22200. this.matrixAutoUpdate = false;
  22201. this.update();
  22202. }
  22203. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  22204. SkeletonHelper.prototype.constructor = SkeletonHelper;
  22205. SkeletonHelper.prototype.getBoneList = function( object ) {
  22206. var boneList = [];
  22207. if ( (object && object.isBone) ) {
  22208. boneList.push( object );
  22209. }
  22210. for ( var i = 0; i < object.children.length; i ++ ) {
  22211. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  22212. }
  22213. return boneList;
  22214. };
  22215. SkeletonHelper.prototype.update = function () {
  22216. var geometry = this.geometry;
  22217. var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld );
  22218. var boneMatrix = new Matrix4();
  22219. var j = 0;
  22220. for ( var i = 0; i < this.bones.length; i ++ ) {
  22221. var bone = this.bones[ i ];
  22222. if ( (bone.parent && bone.parent.isBone) ) {
  22223. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  22224. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  22225. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  22226. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  22227. j += 2;
  22228. }
  22229. }
  22230. geometry.verticesNeedUpdate = true;
  22231. geometry.computeBoundingSphere();
  22232. };
  22233. /**
  22234. * @author benaadams / https://twitter.com/ben_a_adams
  22235. * based on THREE.SphereGeometry
  22236. */
  22237. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22238. BufferGeometry.call( this );
  22239. this.type = 'SphereBufferGeometry';
  22240. this.parameters = {
  22241. radius: radius,
  22242. widthSegments: widthSegments,
  22243. heightSegments: heightSegments,
  22244. phiStart: phiStart,
  22245. phiLength: phiLength,
  22246. thetaStart: thetaStart,
  22247. thetaLength: thetaLength
  22248. };
  22249. radius = radius || 50;
  22250. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22251. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22252. phiStart = phiStart !== undefined ? phiStart : 0;
  22253. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22254. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22255. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22256. var thetaEnd = thetaStart + thetaLength;
  22257. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22258. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22259. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22260. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22261. var index = 0, vertices = [], normal = new Vector3();
  22262. for ( var y = 0; y <= heightSegments; y ++ ) {
  22263. var verticesRow = [];
  22264. var v = y / heightSegments;
  22265. for ( var x = 0; x <= widthSegments; x ++ ) {
  22266. var u = x / widthSegments;
  22267. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22268. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22269. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22270. normal.set( px, py, pz ).normalize();
  22271. positions.setXYZ( index, px, py, pz );
  22272. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22273. uvs.setXY( index, u, 1 - v );
  22274. verticesRow.push( index );
  22275. index ++;
  22276. }
  22277. vertices.push( verticesRow );
  22278. }
  22279. var indices = [];
  22280. for ( var y = 0; y < heightSegments; y ++ ) {
  22281. for ( var x = 0; x < widthSegments; x ++ ) {
  22282. var v1 = vertices[ y ][ x + 1 ];
  22283. var v2 = vertices[ y ][ x ];
  22284. var v3 = vertices[ y + 1 ][ x ];
  22285. var v4 = vertices[ y + 1 ][ x + 1 ];
  22286. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22287. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22288. }
  22289. }
  22290. this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) );
  22291. this.addAttribute( 'position', positions );
  22292. this.addAttribute( 'normal', normals );
  22293. this.addAttribute( 'uv', uvs );
  22294. this.boundingSphere = new Sphere( new Vector3(), radius );
  22295. }
  22296. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22297. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22298. /**
  22299. * @author alteredq / http://alteredqualia.com/
  22300. * @author mrdoob / http://mrdoob.com/
  22301. */
  22302. function PointLightHelper( light, sphereSize ) {
  22303. this.light = light;
  22304. this.light.updateMatrixWorld();
  22305. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  22306. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  22307. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22308. Mesh.call( this, geometry, material );
  22309. this.matrix = this.light.matrixWorld;
  22310. this.matrixAutoUpdate = false;
  22311. /*
  22312. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22313. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22314. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22315. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22316. var d = light.distance;
  22317. if ( d === 0.0 ) {
  22318. this.lightDistance.visible = false;
  22319. } else {
  22320. this.lightDistance.scale.set( d, d, d );
  22321. }
  22322. this.add( this.lightDistance );
  22323. */
  22324. }
  22325. PointLightHelper.prototype = Object.create( Mesh.prototype );
  22326. PointLightHelper.prototype.constructor = PointLightHelper;
  22327. PointLightHelper.prototype.dispose = function () {
  22328. this.geometry.dispose();
  22329. this.material.dispose();
  22330. };
  22331. PointLightHelper.prototype.update = function () {
  22332. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22333. /*
  22334. var d = this.light.distance;
  22335. if ( d === 0.0 ) {
  22336. this.lightDistance.visible = false;
  22337. } else {
  22338. this.lightDistance.visible = true;
  22339. this.lightDistance.scale.set( d, d, d );
  22340. }
  22341. */
  22342. };
  22343. /**
  22344. * @author mrdoob / http://mrdoob.com/
  22345. */
  22346. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22347. Geometry.call( this );
  22348. this.type = 'SphereGeometry';
  22349. this.parameters = {
  22350. radius: radius,
  22351. widthSegments: widthSegments,
  22352. heightSegments: heightSegments,
  22353. phiStart: phiStart,
  22354. phiLength: phiLength,
  22355. thetaStart: thetaStart,
  22356. thetaLength: thetaLength
  22357. };
  22358. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22359. }
  22360. SphereGeometry.prototype = Object.create( Geometry.prototype );
  22361. SphereGeometry.prototype.constructor = SphereGeometry;
  22362. /**
  22363. * @author alteredq / http://alteredqualia.com/
  22364. * @author mrdoob / http://mrdoob.com/
  22365. */
  22366. function HemisphereLightHelper( light, sphereSize ) {
  22367. Object3D.call( this );
  22368. this.light = light;
  22369. this.light.updateMatrixWorld();
  22370. this.matrix = light.matrixWorld;
  22371. this.matrixAutoUpdate = false;
  22372. this.colors = [ new Color(), new Color() ];
  22373. var geometry = new SphereGeometry( sphereSize, 4, 2 );
  22374. geometry.rotateX( - Math.PI / 2 );
  22375. for ( var i = 0, il = 8; i < il; i ++ ) {
  22376. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  22377. }
  22378. var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } );
  22379. this.lightSphere = new Mesh( geometry, material );
  22380. this.add( this.lightSphere );
  22381. this.update();
  22382. }
  22383. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  22384. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  22385. HemisphereLightHelper.prototype.dispose = function () {
  22386. this.lightSphere.geometry.dispose();
  22387. this.lightSphere.material.dispose();
  22388. };
  22389. HemisphereLightHelper.prototype.update = function () {
  22390. var vector = new Vector3();
  22391. return function update() {
  22392. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  22393. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  22394. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22395. this.lightSphere.geometry.colorsNeedUpdate = true;
  22396. };
  22397. }();
  22398. /**
  22399. * @author mrdoob / http://mrdoob.com/
  22400. */
  22401. function GridHelper( size, divisions, color1, color2 ) {
  22402. divisions = divisions || 1;
  22403. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  22404. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  22405. var center = divisions / 2;
  22406. var step = ( size * 2 ) / divisions;
  22407. var vertices = [], colors = [];
  22408. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  22409. vertices.push( - size, 0, k, size, 0, k );
  22410. vertices.push( k, 0, - size, k, 0, size );
  22411. var color = i === center ? color1 : color2;
  22412. color.toArray( colors, j ); j += 3;
  22413. color.toArray( colors, j ); j += 3;
  22414. color.toArray( colors, j ); j += 3;
  22415. color.toArray( colors, j ); j += 3;
  22416. }
  22417. var geometry = new BufferGeometry();
  22418. geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) );
  22419. geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) );
  22420. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  22421. LineSegments.call( this, geometry, material );
  22422. }
  22423. GridHelper.prototype = Object.create( LineSegments.prototype );
  22424. GridHelper.prototype.constructor = GridHelper;
  22425. GridHelper.prototype.setColors = function () {
  22426. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  22427. };
  22428. /**
  22429. * @author mrdoob / http://mrdoob.com/
  22430. * @author WestLangley / http://github.com/WestLangley
  22431. */
  22432. function FaceNormalsHelper( object, size, hex, linewidth ) {
  22433. // FaceNormalsHelper only supports THREE.Geometry
  22434. this.object = object;
  22435. this.size = ( size !== undefined ) ? size : 1;
  22436. var color = ( hex !== undefined ) ? hex : 0xffff00;
  22437. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22438. //
  22439. var nNormals = 0;
  22440. var objGeometry = this.object.geometry;
  22441. if ( (objGeometry && objGeometry.isGeometry) ) {
  22442. nNormals = objGeometry.faces.length;
  22443. } else {
  22444. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  22445. }
  22446. //
  22447. var geometry = new BufferGeometry();
  22448. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  22449. geometry.addAttribute( 'position', positions );
  22450. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22451. //
  22452. this.matrixAutoUpdate = false;
  22453. this.update();
  22454. }
  22455. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22456. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  22457. FaceNormalsHelper.prototype.update = ( function () {
  22458. var v1 = new Vector3();
  22459. var v2 = new Vector3();
  22460. var normalMatrix = new Matrix3();
  22461. return function update() {
  22462. this.object.updateMatrixWorld( true );
  22463. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22464. var matrixWorld = this.object.matrixWorld;
  22465. var position = this.geometry.attributes.position;
  22466. //
  22467. var objGeometry = this.object.geometry;
  22468. var vertices = objGeometry.vertices;
  22469. var faces = objGeometry.faces;
  22470. var idx = 0;
  22471. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22472. var face = faces[ i ];
  22473. var normal = face.normal;
  22474. v1.copy( vertices[ face.a ] )
  22475. .add( vertices[ face.b ] )
  22476. .add( vertices[ face.c ] )
  22477. .divideScalar( 3 )
  22478. .applyMatrix4( matrixWorld );
  22479. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22480. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22481. idx = idx + 1;
  22482. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22483. idx = idx + 1;
  22484. }
  22485. position.needsUpdate = true;
  22486. return this;
  22487. };
  22488. }() );
  22489. /**
  22490. * @author WestLangley / http://github.com/WestLangley
  22491. */
  22492. function EdgesGeometry( geometry, thresholdAngle ) {
  22493. BufferGeometry.call( this );
  22494. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  22495. var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle );
  22496. var edge = [ 0, 0 ], hash = {};
  22497. function sortFunction( a, b ) {
  22498. return a - b;
  22499. }
  22500. var keys = [ 'a', 'b', 'c' ];
  22501. var geometry2;
  22502. if ( (geometry && geometry.isBufferGeometry) ) {
  22503. geometry2 = new Geometry();
  22504. geometry2.fromBufferGeometry( geometry );
  22505. } else {
  22506. geometry2 = geometry.clone();
  22507. }
  22508. geometry2.mergeVertices();
  22509. geometry2.computeFaceNormals();
  22510. var vertices = geometry2.vertices;
  22511. var faces = geometry2.faces;
  22512. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22513. var face = faces[ i ];
  22514. for ( var j = 0; j < 3; j ++ ) {
  22515. edge[ 0 ] = face[ keys[ j ] ];
  22516. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22517. edge.sort( sortFunction );
  22518. var key = edge.toString();
  22519. if ( hash[ key ] === undefined ) {
  22520. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  22521. } else {
  22522. hash[ key ].face2 = i;
  22523. }
  22524. }
  22525. }
  22526. var coords = [];
  22527. for ( var key in hash ) {
  22528. var h = hash[ key ];
  22529. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  22530. var vertex = vertices[ h.vert1 ];
  22531. coords.push( vertex.x );
  22532. coords.push( vertex.y );
  22533. coords.push( vertex.z );
  22534. vertex = vertices[ h.vert2 ];
  22535. coords.push( vertex.x );
  22536. coords.push( vertex.y );
  22537. coords.push( vertex.z );
  22538. }
  22539. }
  22540. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  22541. }
  22542. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  22543. EdgesGeometry.prototype.constructor = EdgesGeometry;
  22544. /**
  22545. * @author WestLangley / http://github.com/WestLangley
  22546. * @param object THREE.Mesh whose geometry will be used
  22547. * @param hex line color
  22548. * @param thresholdAngle the minimum angle (in degrees),
  22549. * between the face normals of adjacent faces,
  22550. * that is required to render an edge. A value of 10 means
  22551. * an edge is only rendered if the angle is at least 10 degrees.
  22552. */
  22553. function EdgesHelper( object, hex, thresholdAngle ) {
  22554. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22555. LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) );
  22556. this.matrix = object.matrixWorld;
  22557. this.matrixAutoUpdate = false;
  22558. }
  22559. EdgesHelper.prototype = Object.create( LineSegments.prototype );
  22560. EdgesHelper.prototype.constructor = EdgesHelper;
  22561. /**
  22562. * @author alteredq / http://alteredqualia.com/
  22563. * @author mrdoob / http://mrdoob.com/
  22564. * @author WestLangley / http://github.com/WestLangley
  22565. */
  22566. function DirectionalLightHelper( light, size ) {
  22567. Object3D.call( this );
  22568. this.light = light;
  22569. this.light.updateMatrixWorld();
  22570. this.matrix = light.matrixWorld;
  22571. this.matrixAutoUpdate = false;
  22572. if ( size === undefined ) size = 1;
  22573. var geometry = new BufferGeometry();
  22574. geometry.addAttribute( 'position', new Float32Attribute( [
  22575. - size, size, 0,
  22576. size, size, 0,
  22577. size, - size, 0,
  22578. - size, - size, 0,
  22579. - size, size, 0
  22580. ], 3 ) );
  22581. var material = new LineBasicMaterial( { fog: false } );
  22582. this.add( new Line( geometry, material ) );
  22583. geometry = new BufferGeometry();
  22584. geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22585. this.add( new Line( geometry, material ));
  22586. this.update();
  22587. }
  22588. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  22589. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  22590. DirectionalLightHelper.prototype.dispose = function () {
  22591. var lightPlane = this.children[ 0 ];
  22592. var targetLine = this.children[ 1 ];
  22593. lightPlane.geometry.dispose();
  22594. lightPlane.material.dispose();
  22595. targetLine.geometry.dispose();
  22596. targetLine.material.dispose();
  22597. };
  22598. DirectionalLightHelper.prototype.update = function () {
  22599. var v1 = new Vector3();
  22600. var v2 = new Vector3();
  22601. var v3 = new Vector3();
  22602. return function update() {
  22603. v1.setFromMatrixPosition( this.light.matrixWorld );
  22604. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22605. v3.subVectors( v2, v1 );
  22606. var lightPlane = this.children[ 0 ];
  22607. var targetLine = this.children[ 1 ];
  22608. lightPlane.lookAt( v3 );
  22609. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22610. targetLine.lookAt( v3 );
  22611. targetLine.scale.z = v3.length();
  22612. };
  22613. }();
  22614. /**
  22615. * @author alteredq / http://alteredqualia.com/
  22616. *
  22617. * - shows frustum, line of sight and up of the camera
  22618. * - suitable for fast updates
  22619. * - based on frustum visualization in lightgl.js shadowmap example
  22620. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  22621. */
  22622. function CameraHelper( camera ) {
  22623. var geometry = new Geometry();
  22624. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  22625. var pointMap = {};
  22626. // colors
  22627. var hexFrustum = 0xffaa00;
  22628. var hexCone = 0xff0000;
  22629. var hexUp = 0x00aaff;
  22630. var hexTarget = 0xffffff;
  22631. var hexCross = 0x333333;
  22632. // near
  22633. addLine( "n1", "n2", hexFrustum );
  22634. addLine( "n2", "n4", hexFrustum );
  22635. addLine( "n4", "n3", hexFrustum );
  22636. addLine( "n3", "n1", hexFrustum );
  22637. // far
  22638. addLine( "f1", "f2", hexFrustum );
  22639. addLine( "f2", "f4", hexFrustum );
  22640. addLine( "f4", "f3", hexFrustum );
  22641. addLine( "f3", "f1", hexFrustum );
  22642. // sides
  22643. addLine( "n1", "f1", hexFrustum );
  22644. addLine( "n2", "f2", hexFrustum );
  22645. addLine( "n3", "f3", hexFrustum );
  22646. addLine( "n4", "f4", hexFrustum );
  22647. // cone
  22648. addLine( "p", "n1", hexCone );
  22649. addLine( "p", "n2", hexCone );
  22650. addLine( "p", "n3", hexCone );
  22651. addLine( "p", "n4", hexCone );
  22652. // up
  22653. addLine( "u1", "u2", hexUp );
  22654. addLine( "u2", "u3", hexUp );
  22655. addLine( "u3", "u1", hexUp );
  22656. // target
  22657. addLine( "c", "t", hexTarget );
  22658. addLine( "p", "c", hexCross );
  22659. // cross
  22660. addLine( "cn1", "cn2", hexCross );
  22661. addLine( "cn3", "cn4", hexCross );
  22662. addLine( "cf1", "cf2", hexCross );
  22663. addLine( "cf3", "cf4", hexCross );
  22664. function addLine( a, b, hex ) {
  22665. addPoint( a, hex );
  22666. addPoint( b, hex );
  22667. }
  22668. function addPoint( id, hex ) {
  22669. geometry.vertices.push( new Vector3() );
  22670. geometry.colors.push( new Color( hex ) );
  22671. if ( pointMap[ id ] === undefined ) {
  22672. pointMap[ id ] = [];
  22673. }
  22674. pointMap[ id ].push( geometry.vertices.length - 1 );
  22675. }
  22676. LineSegments.call( this, geometry, material );
  22677. this.camera = camera;
  22678. if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22679. this.matrix = camera.matrixWorld;
  22680. this.matrixAutoUpdate = false;
  22681. this.pointMap = pointMap;
  22682. this.update();
  22683. }
  22684. CameraHelper.prototype = Object.create( LineSegments.prototype );
  22685. CameraHelper.prototype.constructor = CameraHelper;
  22686. CameraHelper.prototype.update = function () {
  22687. var geometry, pointMap;
  22688. var vector = new Vector3();
  22689. var camera = new Camera();
  22690. function setPoint( point, x, y, z ) {
  22691. vector.set( x, y, z ).unproject( camera );
  22692. var points = pointMap[ point ];
  22693. if ( points !== undefined ) {
  22694. for ( var i = 0, il = points.length; i < il; i ++ ) {
  22695. geometry.vertices[ points[ i ] ].copy( vector );
  22696. }
  22697. }
  22698. }
  22699. return function update() {
  22700. geometry = this.geometry;
  22701. pointMap = this.pointMap;
  22702. var w = 1, h = 1;
  22703. // we need just camera projection matrix
  22704. // world matrix must be identity
  22705. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  22706. // center / target
  22707. setPoint( "c", 0, 0, - 1 );
  22708. setPoint( "t", 0, 0, 1 );
  22709. // near
  22710. setPoint( "n1", - w, - h, - 1 );
  22711. setPoint( "n2", w, - h, - 1 );
  22712. setPoint( "n3", - w, h, - 1 );
  22713. setPoint( "n4", w, h, - 1 );
  22714. // far
  22715. setPoint( "f1", - w, - h, 1 );
  22716. setPoint( "f2", w, - h, 1 );
  22717. setPoint( "f3", - w, h, 1 );
  22718. setPoint( "f4", w, h, 1 );
  22719. // up
  22720. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  22721. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  22722. setPoint( "u3", 0, h * 2, - 1 );
  22723. // cross
  22724. setPoint( "cf1", - w, 0, 1 );
  22725. setPoint( "cf2", w, 0, 1 );
  22726. setPoint( "cf3", 0, - h, 1 );
  22727. setPoint( "cf4", 0, h, 1 );
  22728. setPoint( "cn1", - w, 0, - 1 );
  22729. setPoint( "cn2", w, 0, - 1 );
  22730. setPoint( "cn3", 0, - h, - 1 );
  22731. setPoint( "cn4", 0, h, - 1 );
  22732. geometry.verticesNeedUpdate = true;
  22733. };
  22734. }();
  22735. /**
  22736. * @author mrdoob / http://mrdoob.com/
  22737. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  22738. */
  22739. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  22740. Geometry.call( this );
  22741. this.type = 'BoxGeometry';
  22742. this.parameters = {
  22743. width: width,
  22744. height: height,
  22745. depth: depth,
  22746. widthSegments: widthSegments,
  22747. heightSegments: heightSegments,
  22748. depthSegments: depthSegments
  22749. };
  22750. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  22751. this.mergeVertices();
  22752. }
  22753. BoxGeometry.prototype = Object.create( Geometry.prototype );
  22754. BoxGeometry.prototype.constructor = BoxGeometry;
  22755. /**
  22756. * @author WestLangley / http://github.com/WestLangley
  22757. */
  22758. // a helper to show the world-axis-aligned bounding box for an object
  22759. function BoundingBoxHelper( object, hex ) {
  22760. var color = ( hex !== undefined ) ? hex : 0x888888;
  22761. this.object = object;
  22762. this.box = new Box3();
  22763. Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) );
  22764. }
  22765. BoundingBoxHelper.prototype = Object.create( Mesh.prototype );
  22766. BoundingBoxHelper.prototype.constructor = BoundingBoxHelper;
  22767. BoundingBoxHelper.prototype.update = function () {
  22768. this.box.setFromObject( this.object );
  22769. this.box.size( this.scale );
  22770. this.box.center( this.position );
  22771. };
  22772. /**
  22773. * @author mrdoob / http://mrdoob.com/
  22774. */
  22775. function BoxHelper( object, color ) {
  22776. if ( color === undefined ) color = 0xffff00;
  22777. 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 ] );
  22778. var positions = new Float32Array( 8 * 3 );
  22779. var geometry = new BufferGeometry();
  22780. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  22781. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  22782. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  22783. if ( object !== undefined ) {
  22784. this.update( object );
  22785. }
  22786. }
  22787. BoxHelper.prototype = Object.create( LineSegments.prototype );
  22788. BoxHelper.prototype.constructor = BoxHelper;
  22789. BoxHelper.prototype.update = ( function () {
  22790. var box = new Box3();
  22791. return function update( object ) {
  22792. if ( (object && object.isBox3) ) {
  22793. box.copy( object );
  22794. } else {
  22795. box.setFromObject( object );
  22796. }
  22797. if ( box.isEmpty() ) return;
  22798. var min = box.min;
  22799. var max = box.max;
  22800. /*
  22801. 5____4
  22802. 1/___0/|
  22803. | 6__|_7
  22804. 2/___3/
  22805. 0: max.x, max.y, max.z
  22806. 1: min.x, max.y, max.z
  22807. 2: min.x, min.y, max.z
  22808. 3: max.x, min.y, max.z
  22809. 4: max.x, max.y, min.z
  22810. 5: min.x, max.y, min.z
  22811. 6: min.x, min.y, min.z
  22812. 7: max.x, min.y, min.z
  22813. */
  22814. var position = this.geometry.attributes.position;
  22815. var array = position.array;
  22816. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  22817. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  22818. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  22819. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  22820. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  22821. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  22822. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  22823. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  22824. position.needsUpdate = true;
  22825. this.geometry.computeBoundingSphere();
  22826. };
  22827. } )();
  22828. /**
  22829. * @author Mugen87 / https://github.com/Mugen87
  22830. */
  22831. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22832. BufferGeometry.call( this );
  22833. this.type = 'CylinderBufferGeometry';
  22834. this.parameters = {
  22835. radiusTop: radiusTop,
  22836. radiusBottom: radiusBottom,
  22837. height: height,
  22838. radialSegments: radialSegments,
  22839. heightSegments: heightSegments,
  22840. openEnded: openEnded,
  22841. thetaStart: thetaStart,
  22842. thetaLength: thetaLength
  22843. };
  22844. var scope = this;
  22845. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  22846. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  22847. height = height !== undefined ? height : 100;
  22848. radialSegments = Math.floor( radialSegments ) || 8;
  22849. heightSegments = Math.floor( heightSegments ) || 1;
  22850. openEnded = openEnded !== undefined ? openEnded : false;
  22851. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  22852. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  22853. // used to calculate buffer length
  22854. var nbCap = 0;
  22855. if ( openEnded === false ) {
  22856. if ( radiusTop > 0 ) nbCap ++;
  22857. if ( radiusBottom > 0 ) nbCap ++;
  22858. }
  22859. var vertexCount = calculateVertexCount();
  22860. var indexCount = calculateIndexCount();
  22861. // buffers
  22862. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  22863. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22864. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22865. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22866. // helper variables
  22867. var index = 0,
  22868. indexOffset = 0,
  22869. indexArray = [],
  22870. halfHeight = height / 2;
  22871. // group variables
  22872. var groupStart = 0;
  22873. // generate geometry
  22874. generateTorso();
  22875. if ( openEnded === false ) {
  22876. if ( radiusTop > 0 ) generateCap( true );
  22877. if ( radiusBottom > 0 ) generateCap( false );
  22878. }
  22879. // build geometry
  22880. this.setIndex( indices );
  22881. this.addAttribute( 'position', vertices );
  22882. this.addAttribute( 'normal', normals );
  22883. this.addAttribute( 'uv', uvs );
  22884. // helper functions
  22885. function calculateVertexCount() {
  22886. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  22887. if ( openEnded === false ) {
  22888. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  22889. }
  22890. return count;
  22891. }
  22892. function calculateIndexCount() {
  22893. var count = radialSegments * heightSegments * 2 * 3;
  22894. if ( openEnded === false ) {
  22895. count += radialSegments * nbCap * 3;
  22896. }
  22897. return count;
  22898. }
  22899. function generateTorso() {
  22900. var x, y;
  22901. var normal = new Vector3();
  22902. var vertex = new Vector3();
  22903. var groupCount = 0;
  22904. // this will be used to calculate the normal
  22905. var tanTheta = ( radiusBottom - radiusTop ) / height;
  22906. // generate vertices, normals and uvs
  22907. for ( y = 0; y <= heightSegments; y ++ ) {
  22908. var indexRow = [];
  22909. var v = y / heightSegments;
  22910. // calculate the radius of the current row
  22911. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22912. for ( x = 0; x <= radialSegments; x ++ ) {
  22913. var u = x / radialSegments;
  22914. // vertex
  22915. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  22916. vertex.y = - v * height + halfHeight;
  22917. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  22918. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22919. // normal
  22920. normal.copy( vertex );
  22921. // handle special case if radiusTop/radiusBottom is zero
  22922. if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  22923. normal.x = Math.sin( u * thetaLength + thetaStart );
  22924. normal.z = Math.cos( u * thetaLength + thetaStart );
  22925. }
  22926. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  22927. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22928. // uv
  22929. uvs.setXY( index, u, 1 - v );
  22930. // save index of vertex in respective row
  22931. indexRow.push( index );
  22932. // increase index
  22933. index ++;
  22934. }
  22935. // now save vertices of the row in our index array
  22936. indexArray.push( indexRow );
  22937. }
  22938. // generate indices
  22939. for ( x = 0; x < radialSegments; x ++ ) {
  22940. for ( y = 0; y < heightSegments; y ++ ) {
  22941. // we use the index array to access the correct indices
  22942. var i1 = indexArray[ y ][ x ];
  22943. var i2 = indexArray[ y + 1 ][ x ];
  22944. var i3 = indexArray[ y + 1 ][ x + 1 ];
  22945. var i4 = indexArray[ y ][ x + 1 ];
  22946. // face one
  22947. indices.setX( indexOffset, i1 ); indexOffset ++;
  22948. indices.setX( indexOffset, i2 ); indexOffset ++;
  22949. indices.setX( indexOffset, i4 ); indexOffset ++;
  22950. // face two
  22951. indices.setX( indexOffset, i2 ); indexOffset ++;
  22952. indices.setX( indexOffset, i3 ); indexOffset ++;
  22953. indices.setX( indexOffset, i4 ); indexOffset ++;
  22954. // update counters
  22955. groupCount += 6;
  22956. }
  22957. }
  22958. // add a group to the geometry. this will ensure multi material support
  22959. scope.addGroup( groupStart, groupCount, 0 );
  22960. // calculate new start value for groups
  22961. groupStart += groupCount;
  22962. }
  22963. function generateCap( top ) {
  22964. var x, centerIndexStart, centerIndexEnd;
  22965. var uv = new Vector2();
  22966. var vertex = new Vector3();
  22967. var groupCount = 0;
  22968. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22969. var sign = ( top === true ) ? 1 : - 1;
  22970. // save the index of the first center vertex
  22971. centerIndexStart = index;
  22972. // first we generate the center vertex data of the cap.
  22973. // because the geometry needs one set of uvs per face,
  22974. // we must generate a center vertex per face/segment
  22975. for ( x = 1; x <= radialSegments; x ++ ) {
  22976. // vertex
  22977. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  22978. // normal
  22979. normals.setXYZ( index, 0, sign, 0 );
  22980. // uv
  22981. uv.x = 0.5;
  22982. uv.y = 0.5;
  22983. uvs.setXY( index, uv.x, uv.y );
  22984. // increase index
  22985. index ++;
  22986. }
  22987. // save the index of the last center vertex
  22988. centerIndexEnd = index;
  22989. // now we generate the surrounding vertices, normals and uvs
  22990. for ( x = 0; x <= radialSegments; x ++ ) {
  22991. var u = x / radialSegments;
  22992. var theta = u * thetaLength + thetaStart;
  22993. var cosTheta = Math.cos( theta );
  22994. var sinTheta = Math.sin( theta );
  22995. // vertex
  22996. vertex.x = radius * sinTheta;
  22997. vertex.y = halfHeight * sign;
  22998. vertex.z = radius * cosTheta;
  22999. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23000. // normal
  23001. normals.setXYZ( index, 0, sign, 0 );
  23002. // uv
  23003. uv.x = ( cosTheta * 0.5 ) + 0.5;
  23004. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  23005. uvs.setXY( index, uv.x, uv.y );
  23006. // increase index
  23007. index ++;
  23008. }
  23009. // generate indices
  23010. for ( x = 0; x < radialSegments; x ++ ) {
  23011. var c = centerIndexStart + x;
  23012. var i = centerIndexEnd + x;
  23013. if ( top === true ) {
  23014. // face top
  23015. indices.setX( indexOffset, i ); indexOffset ++;
  23016. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  23017. indices.setX( indexOffset, c ); indexOffset ++;
  23018. } else {
  23019. // face bottom
  23020. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  23021. indices.setX( indexOffset, i ); indexOffset ++;
  23022. indices.setX( indexOffset, c ); indexOffset ++;
  23023. }
  23024. // update counters
  23025. groupCount += 3;
  23026. }
  23027. // add a group to the geometry. this will ensure multi material support
  23028. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23029. // calculate new start value for groups
  23030. groupStart += groupCount;
  23031. }
  23032. }
  23033. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23034. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  23035. var lineGeometry = new BufferGeometry();
  23036. lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  23037. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  23038. coneGeometry.translate( 0, - 0.5, 0 );
  23039. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  23040. // dir is assumed to be normalized
  23041. Object3D.call( this );
  23042. if ( color === undefined ) color = 0xffff00;
  23043. if ( length === undefined ) length = 1;
  23044. if ( headLength === undefined ) headLength = 0.2 * length;
  23045. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23046. this.position.copy( origin );
  23047. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  23048. this.line.matrixAutoUpdate = false;
  23049. this.add( this.line );
  23050. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  23051. this.cone.matrixAutoUpdate = false;
  23052. this.add( this.cone );
  23053. this.setDirection( dir );
  23054. this.setLength( length, headLength, headWidth );
  23055. }
  23056. ArrowHelper.prototype = Object.create( Object3D.prototype );
  23057. ArrowHelper.prototype.constructor = ArrowHelper;
  23058. ArrowHelper.prototype.setDirection = ( function () {
  23059. var axis = new Vector3();
  23060. var radians;
  23061. return function setDirection( dir ) {
  23062. // dir is assumed to be normalized
  23063. if ( dir.y > 0.99999 ) {
  23064. this.quaternion.set( 0, 0, 0, 1 );
  23065. } else if ( dir.y < - 0.99999 ) {
  23066. this.quaternion.set( 1, 0, 0, 0 );
  23067. } else {
  23068. axis.set( dir.z, 0, - dir.x ).normalize();
  23069. radians = Math.acos( dir.y );
  23070. this.quaternion.setFromAxisAngle( axis, radians );
  23071. }
  23072. };
  23073. }() );
  23074. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  23075. if ( headLength === undefined ) headLength = 0.2 * length;
  23076. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23077. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  23078. this.line.updateMatrix();
  23079. this.cone.scale.set( headWidth, headLength, headWidth );
  23080. this.cone.position.y = length;
  23081. this.cone.updateMatrix();
  23082. };
  23083. ArrowHelper.prototype.setColor = function ( color ) {
  23084. this.line.material.color.copy( color );
  23085. this.cone.material.color.copy( color );
  23086. };
  23087. /**
  23088. * @author sroucheray / http://sroucheray.org/
  23089. * @author mrdoob / http://mrdoob.com/
  23090. */
  23091. function AxisHelper( size ) {
  23092. size = size || 1;
  23093. var vertices = new Float32Array( [
  23094. 0, 0, 0, size, 0, 0,
  23095. 0, 0, 0, 0, size, 0,
  23096. 0, 0, 0, 0, 0, size
  23097. ] );
  23098. var colors = new Float32Array( [
  23099. 1, 0, 0, 1, 0.6, 0,
  23100. 0, 1, 0, 0.6, 1, 0,
  23101. 0, 0, 1, 0, 0.6, 1
  23102. ] );
  23103. var geometry = new BufferGeometry();
  23104. geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23105. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  23106. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  23107. LineSegments.call( this, geometry, material );
  23108. }
  23109. AxisHelper.prototype = Object.create( LineSegments.prototype );
  23110. AxisHelper.prototype.constructor = AxisHelper;
  23111. /**
  23112. * @author zz85 / https://github.com/zz85
  23113. * Parametric Surfaces Geometry
  23114. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23115. *
  23116. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23117. *
  23118. */
  23119. function ParametricGeometry( func, slices, stacks ) {
  23120. Geometry.call( this );
  23121. this.type = 'ParametricGeometry';
  23122. this.parameters = {
  23123. func: func,
  23124. slices: slices,
  23125. stacks: stacks
  23126. };
  23127. var verts = this.vertices;
  23128. var faces = this.faces;
  23129. var uvs = this.faceVertexUvs[ 0 ];
  23130. var i, j, p;
  23131. var u, v;
  23132. var sliceCount = slices + 1;
  23133. for ( i = 0; i <= stacks; i ++ ) {
  23134. v = i / stacks;
  23135. for ( j = 0; j <= slices; j ++ ) {
  23136. u = j / slices;
  23137. p = func( u, v );
  23138. verts.push( p );
  23139. }
  23140. }
  23141. var a, b, c, d;
  23142. var uva, uvb, uvc, uvd;
  23143. for ( i = 0; i < stacks; i ++ ) {
  23144. for ( j = 0; j < slices; j ++ ) {
  23145. a = i * sliceCount + j;
  23146. b = i * sliceCount + j + 1;
  23147. c = ( i + 1 ) * sliceCount + j + 1;
  23148. d = ( i + 1 ) * sliceCount + j;
  23149. uva = new Vector2( j / slices, i / stacks );
  23150. uvb = new Vector2( ( j + 1 ) / slices, i / stacks );
  23151. uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23152. uvd = new Vector2( j / slices, ( i + 1 ) / stacks );
  23153. faces.push( new Face3( a, b, d ) );
  23154. uvs.push( [ uva, uvb, uvd ] );
  23155. faces.push( new Face3( b, c, d ) );
  23156. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23157. }
  23158. }
  23159. // console.log(this);
  23160. // magic bullet
  23161. // var diff = this.mergeVertices();
  23162. // console.log('removed ', diff, ' vertices by merging');
  23163. this.computeFaceNormals();
  23164. this.computeVertexNormals();
  23165. }
  23166. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  23167. ParametricGeometry.prototype.constructor = ParametricGeometry;
  23168. /**
  23169. * @author clockworkgeek / https://github.com/clockworkgeek
  23170. * @author timothypratley / https://github.com/timothypratley
  23171. * @author WestLangley / http://github.com/WestLangley
  23172. */
  23173. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  23174. Geometry.call( this );
  23175. this.type = 'PolyhedronGeometry';
  23176. this.parameters = {
  23177. vertices: vertices,
  23178. indices: indices,
  23179. radius: radius,
  23180. detail: detail
  23181. };
  23182. radius = radius || 1;
  23183. detail = detail || 0;
  23184. var that = this;
  23185. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  23186. prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  23187. }
  23188. var p = this.vertices;
  23189. var faces = [];
  23190. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  23191. var v1 = p[ indices[ i ] ];
  23192. var v2 = p[ indices[ i + 1 ] ];
  23193. var v3 = p[ indices[ i + 2 ] ];
  23194. faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23195. }
  23196. var centroid = new Vector3();
  23197. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23198. subdivide( faces[ i ], detail );
  23199. }
  23200. // Handle case when face straddles the seam
  23201. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  23202. var uvs = this.faceVertexUvs[ 0 ][ i ];
  23203. var x0 = uvs[ 0 ].x;
  23204. var x1 = uvs[ 1 ].x;
  23205. var x2 = uvs[ 2 ].x;
  23206. var max = Math.max( x0, x1, x2 );
  23207. var min = Math.min( x0, x1, x2 );
  23208. if ( max > 0.9 && min < 0.1 ) {
  23209. // 0.9 is somewhat arbitrary
  23210. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  23211. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  23212. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  23213. }
  23214. }
  23215. // Apply radius
  23216. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  23217. this.vertices[ i ].multiplyScalar( radius );
  23218. }
  23219. // Merge vertices
  23220. this.mergeVertices();
  23221. this.computeFaceNormals();
  23222. this.boundingSphere = new Sphere( new Vector3(), radius );
  23223. // Project vector onto sphere's surface
  23224. function prepare( vector ) {
  23225. var vertex = vector.normalize().clone();
  23226. vertex.index = that.vertices.push( vertex ) - 1;
  23227. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  23228. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  23229. var v = inclination( vector ) / Math.PI + 0.5;
  23230. vertex.uv = new Vector2( u, 1 - v );
  23231. return vertex;
  23232. }
  23233. // Approximate a curved face with recursively sub-divided triangles.
  23234. function make( v1, v2, v3 ) {
  23235. var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23236. that.faces.push( face );
  23237. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  23238. var azi = azimuth( centroid );
  23239. that.faceVertexUvs[ 0 ].push( [
  23240. correctUV( v1.uv, v1, azi ),
  23241. correctUV( v2.uv, v2, azi ),
  23242. correctUV( v3.uv, v3, azi )
  23243. ] );
  23244. }
  23245. // Analytically subdivide a face to the required detail level.
  23246. function subdivide( face, detail ) {
  23247. var cols = Math.pow( 2, detail );
  23248. var a = prepare( that.vertices[ face.a ] );
  23249. var b = prepare( that.vertices[ face.b ] );
  23250. var c = prepare( that.vertices[ face.c ] );
  23251. var v = [];
  23252. // Construct all of the vertices for this subdivision.
  23253. for ( var i = 0 ; i <= cols; i ++ ) {
  23254. v[ i ] = [];
  23255. var aj = prepare( a.clone().lerp( c, i / cols ) );
  23256. var bj = prepare( b.clone().lerp( c, i / cols ) );
  23257. var rows = cols - i;
  23258. for ( var j = 0; j <= rows; j ++ ) {
  23259. if ( j === 0 && i === cols ) {
  23260. v[ i ][ j ] = aj;
  23261. } else {
  23262. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  23263. }
  23264. }
  23265. }
  23266. // Construct all of the faces.
  23267. for ( var i = 0; i < cols ; i ++ ) {
  23268. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23269. var k = Math.floor( j / 2 );
  23270. if ( j % 2 === 0 ) {
  23271. make(
  23272. v[ i ][ k + 1 ],
  23273. v[ i + 1 ][ k ],
  23274. v[ i ][ k ]
  23275. );
  23276. } else {
  23277. make(
  23278. v[ i ][ k + 1 ],
  23279. v[ i + 1 ][ k + 1 ],
  23280. v[ i + 1 ][ k ]
  23281. );
  23282. }
  23283. }
  23284. }
  23285. }
  23286. // Angle around the Y axis, counter-clockwise when looking from above.
  23287. function azimuth( vector ) {
  23288. return Math.atan2( vector.z, - vector.x );
  23289. }
  23290. // Angle above the XZ plane.
  23291. function inclination( vector ) {
  23292. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23293. }
  23294. // Texture fixing helper. Spheres have some odd behaviours.
  23295. function correctUV( uv, vector, azimuth ) {
  23296. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y );
  23297. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  23298. return uv.clone();
  23299. }
  23300. }
  23301. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  23302. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  23303. /**
  23304. * @author timothypratley / https://github.com/timothypratley
  23305. */
  23306. function TetrahedronGeometry( radius, detail ) {
  23307. var vertices = [
  23308. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23309. ];
  23310. var indices = [
  23311. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23312. ];
  23313. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23314. this.type = 'TetrahedronGeometry';
  23315. this.parameters = {
  23316. radius: radius,
  23317. detail: detail
  23318. };
  23319. }
  23320. TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23321. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  23322. /**
  23323. * @author timothypratley / https://github.com/timothypratley
  23324. */
  23325. function OctahedronGeometry( radius, detail ) {
  23326. var vertices = [
  23327. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23328. ];
  23329. var indices = [
  23330. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  23331. ];
  23332. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23333. this.type = 'OctahedronGeometry';
  23334. this.parameters = {
  23335. radius: radius,
  23336. detail: detail
  23337. };
  23338. }
  23339. OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23340. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  23341. /**
  23342. * @author timothypratley / https://github.com/timothypratley
  23343. */
  23344. function IcosahedronGeometry( radius, detail ) {
  23345. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23346. var vertices = [
  23347. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23348. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23349. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23350. ];
  23351. var indices = [
  23352. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23353. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23354. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23355. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23356. ];
  23357. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23358. this.type = 'IcosahedronGeometry';
  23359. this.parameters = {
  23360. radius: radius,
  23361. detail: detail
  23362. };
  23363. }
  23364. IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23365. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  23366. /**
  23367. * @author Abe Pazos / https://hamoid.com
  23368. */
  23369. function DodecahedronGeometry( radius, detail ) {
  23370. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23371. var r = 1 / t;
  23372. var vertices = [
  23373. // (±1, ±1, ±1)
  23374. - 1, - 1, - 1, - 1, - 1, 1,
  23375. - 1, 1, - 1, - 1, 1, 1,
  23376. 1, - 1, - 1, 1, - 1, 1,
  23377. 1, 1, - 1, 1, 1, 1,
  23378. // (0, ±1/φ, ±φ)
  23379. 0, - r, - t, 0, - r, t,
  23380. 0, r, - t, 0, r, t,
  23381. // (±1/φ, ±φ, 0)
  23382. - r, - t, 0, - r, t, 0,
  23383. r, - t, 0, r, t, 0,
  23384. // (±φ, 0, ±1/φ)
  23385. - t, 0, - r, t, 0, - r,
  23386. - t, 0, r, t, 0, r
  23387. ];
  23388. var indices = [
  23389. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23390. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23391. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23392. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23393. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23394. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23395. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23396. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23397. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23398. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23399. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23400. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23401. ];
  23402. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23403. this.type = 'DodecahedronGeometry';
  23404. this.parameters = {
  23405. radius: radius,
  23406. detail: detail
  23407. };
  23408. }
  23409. DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23410. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  23411. /**
  23412. * @author Mugen87 / https://github.com/Mugen87
  23413. *
  23414. * see: http://www.blackpawn.com/texts/pqtorus/
  23415. */
  23416. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  23417. BufferGeometry.call( this );
  23418. this.type = 'TorusKnotBufferGeometry';
  23419. this.parameters = {
  23420. radius: radius,
  23421. tube: tube,
  23422. tubularSegments: tubularSegments,
  23423. radialSegments: radialSegments,
  23424. p: p,
  23425. q: q
  23426. };
  23427. radius = radius || 100;
  23428. tube = tube || 40;
  23429. tubularSegments = Math.floor( tubularSegments ) || 64;
  23430. radialSegments = Math.floor( radialSegments ) || 8;
  23431. p = p || 2;
  23432. q = q || 3;
  23433. // used to calculate buffer length
  23434. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23435. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23436. // buffers
  23437. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23438. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23439. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23440. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23441. // helper variables
  23442. var i, j, index = 0, indexOffset = 0;
  23443. var vertex = new Vector3();
  23444. var normal = new Vector3();
  23445. var uv = new Vector2();
  23446. var P1 = new Vector3();
  23447. var P2 = new Vector3();
  23448. var B = new Vector3();
  23449. var T = new Vector3();
  23450. var N = new Vector3();
  23451. // generate vertices, normals and uvs
  23452. for ( i = 0; i <= tubularSegments; ++ i ) {
  23453. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23454. var u = i / tubularSegments * p * Math.PI * 2;
  23455. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23456. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23457. calculatePositionOnCurve( u, p, q, radius, P1 );
  23458. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23459. // calculate orthonormal basis
  23460. T.subVectors( P2, P1 );
  23461. N.addVectors( P2, P1 );
  23462. B.crossVectors( T, N );
  23463. N.crossVectors( B, T );
  23464. // normalize B, N. T can be ignored, we don't use it
  23465. B.normalize();
  23466. N.normalize();
  23467. for ( j = 0; j <= radialSegments; ++ j ) {
  23468. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23469. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23470. var v = j / radialSegments * Math.PI * 2;
  23471. var cx = - tube * Math.cos( v );
  23472. var cy = tube * Math.sin( v );
  23473. // now calculate the final vertex position.
  23474. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23475. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23476. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23477. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23478. // vertex
  23479. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23480. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23481. normal.subVectors( vertex, P1 ).normalize();
  23482. normals.setXYZ( index, normal.x, normal.y, normal.z );
  23483. // uv
  23484. uv.x = i / tubularSegments;
  23485. uv.y = j / radialSegments;
  23486. uvs.setXY( index, uv.x, uv.y );
  23487. // increase index
  23488. index ++;
  23489. }
  23490. }
  23491. // generate indices
  23492. for ( j = 1; j <= tubularSegments; j ++ ) {
  23493. for ( i = 1; i <= radialSegments; i ++ ) {
  23494. // indices
  23495. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23496. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23497. var c = ( radialSegments + 1 ) * j + i;
  23498. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23499. // face one
  23500. indices.setX( indexOffset, a ); indexOffset++;
  23501. indices.setX( indexOffset, b ); indexOffset++;
  23502. indices.setX( indexOffset, d ); indexOffset++;
  23503. // face two
  23504. indices.setX( indexOffset, b ); indexOffset++;
  23505. indices.setX( indexOffset, c ); indexOffset++;
  23506. indices.setX( indexOffset, d ); indexOffset++;
  23507. }
  23508. }
  23509. // build geometry
  23510. this.setIndex( indices );
  23511. this.addAttribute( 'position', vertices );
  23512. this.addAttribute( 'normal', normals );
  23513. this.addAttribute( 'uv', uvs );
  23514. // this function calculates the current position on the torus curve
  23515. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23516. var cu = Math.cos( u );
  23517. var su = Math.sin( u );
  23518. var quOverP = q / p * u;
  23519. var cs = Math.cos( quOverP );
  23520. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23521. position.y = radius * ( 2 + cs ) * su * 0.5;
  23522. position.z = radius * Math.sin( quOverP ) * 0.5;
  23523. }
  23524. }
  23525. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23526. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  23527. /**
  23528. * @author oosmoxiecode
  23529. */
  23530. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23531. Geometry.call( this );
  23532. this.type = 'TorusKnotGeometry';
  23533. this.parameters = {
  23534. radius: radius,
  23535. tube: tube,
  23536. tubularSegments: tubularSegments,
  23537. radialSegments: radialSegments,
  23538. p: p,
  23539. q: q
  23540. };
  23541. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  23542. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23543. this.mergeVertices();
  23544. }
  23545. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  23546. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  23547. /**
  23548. * @author Mugen87 / https://github.com/Mugen87
  23549. */
  23550. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23551. BufferGeometry.call( this );
  23552. this.type = 'TorusBufferGeometry';
  23553. this.parameters = {
  23554. radius: radius,
  23555. tube: tube,
  23556. radialSegments: radialSegments,
  23557. tubularSegments: tubularSegments,
  23558. arc: arc
  23559. };
  23560. radius = radius || 100;
  23561. tube = tube || 40;
  23562. radialSegments = Math.floor( radialSegments ) || 8;
  23563. tubularSegments = Math.floor( tubularSegments ) || 6;
  23564. arc = arc || Math.PI * 2;
  23565. // used to calculate buffer length
  23566. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23567. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23568. // buffers
  23569. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  23570. var vertices = new Float32Array( vertexCount * 3 );
  23571. var normals = new Float32Array( vertexCount * 3 );
  23572. var uvs = new Float32Array( vertexCount * 2 );
  23573. // offset variables
  23574. var vertexBufferOffset = 0;
  23575. var uvBufferOffset = 0;
  23576. var indexBufferOffset = 0;
  23577. // helper variables
  23578. var center = new Vector3();
  23579. var vertex = new Vector3();
  23580. var normal = new Vector3();
  23581. var j, i;
  23582. // generate vertices, normals and uvs
  23583. for ( j = 0; j <= radialSegments; j ++ ) {
  23584. for ( i = 0; i <= tubularSegments; i ++ ) {
  23585. var u = i / tubularSegments * arc;
  23586. var v = j / radialSegments * Math.PI * 2;
  23587. // vertex
  23588. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23589. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23590. vertex.z = tube * Math.sin( v );
  23591. vertices[ vertexBufferOffset ] = vertex.x;
  23592. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  23593. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  23594. // this vector is used to calculate the normal
  23595. center.x = radius * Math.cos( u );
  23596. center.y = radius * Math.sin( u );
  23597. // normal
  23598. normal.subVectors( vertex, center ).normalize();
  23599. normals[ vertexBufferOffset ] = normal.x;
  23600. normals[ vertexBufferOffset + 1 ] = normal.y;
  23601. normals[ vertexBufferOffset + 2 ] = normal.z;
  23602. // uv
  23603. uvs[ uvBufferOffset ] = i / tubularSegments;
  23604. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  23605. // update offsets
  23606. vertexBufferOffset += 3;
  23607. uvBufferOffset += 2;
  23608. }
  23609. }
  23610. // generate indices
  23611. for ( j = 1; j <= radialSegments; j ++ ) {
  23612. for ( i = 1; i <= tubularSegments; i ++ ) {
  23613. // indices
  23614. var a = ( tubularSegments + 1 ) * j + i - 1;
  23615. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23616. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23617. var d = ( tubularSegments + 1 ) * j + i;
  23618. // face one
  23619. indices[ indexBufferOffset ] = a;
  23620. indices[ indexBufferOffset + 1 ] = b;
  23621. indices[ indexBufferOffset + 2 ] = d;
  23622. // face two
  23623. indices[ indexBufferOffset + 3 ] = b;
  23624. indices[ indexBufferOffset + 4 ] = c;
  23625. indices[ indexBufferOffset + 5 ] = d;
  23626. // update offset
  23627. indexBufferOffset += 6;
  23628. }
  23629. }
  23630. // build geometry
  23631. this.setIndex( new BufferAttribute( indices, 1 ) );
  23632. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23633. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  23634. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  23635. }
  23636. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23637. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  23638. /**
  23639. * @author oosmoxiecode
  23640. * @author mrdoob / http://mrdoob.com/
  23641. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  23642. */
  23643. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23644. Geometry.call( this );
  23645. this.type = 'TorusGeometry';
  23646. this.parameters = {
  23647. radius: radius,
  23648. tube: tube,
  23649. radialSegments: radialSegments,
  23650. tubularSegments: tubularSegments,
  23651. arc: arc
  23652. };
  23653. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23654. }
  23655. TorusGeometry.prototype = Object.create( Geometry.prototype );
  23656. TorusGeometry.prototype.constructor = TorusGeometry;
  23657. /**
  23658. * @author zz85 / http://www.lab4games.net/zz85/blog
  23659. * @author alteredq / http://alteredqualia.com/
  23660. *
  23661. * Text = 3D Text
  23662. *
  23663. * parameters = {
  23664. * font: <THREE.Font>, // font
  23665. *
  23666. * size: <float>, // size of the text
  23667. * height: <float>, // thickness to extrude text
  23668. * curveSegments: <int>, // number of points on the curves
  23669. *
  23670. * bevelEnabled: <bool>, // turn on bevel
  23671. * bevelThickness: <float>, // how deep into text bevel goes
  23672. * bevelSize: <float> // how far from text outline is bevel
  23673. * }
  23674. */
  23675. function TextGeometry( text, parameters ) {
  23676. parameters = parameters || {};
  23677. var font = parameters.font;
  23678. if ( (font && font.isFont) === false ) {
  23679. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  23680. return new Geometry();
  23681. }
  23682. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  23683. // translate parameters to ExtrudeGeometry API
  23684. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  23685. // defaults
  23686. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  23687. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  23688. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  23689. ExtrudeGeometry.call( this, shapes, parameters );
  23690. this.type = 'TextGeometry';
  23691. }
  23692. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  23693. TextGeometry.prototype.constructor = TextGeometry;
  23694. /**
  23695. * @author Mugen87 / https://github.com/Mugen87
  23696. */
  23697. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23698. BufferGeometry.call( this );
  23699. this.type = 'RingBufferGeometry';
  23700. this.parameters = {
  23701. innerRadius: innerRadius,
  23702. outerRadius: outerRadius,
  23703. thetaSegments: thetaSegments,
  23704. phiSegments: phiSegments,
  23705. thetaStart: thetaStart,
  23706. thetaLength: thetaLength
  23707. };
  23708. innerRadius = innerRadius || 20;
  23709. outerRadius = outerRadius || 50;
  23710. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23711. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23712. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  23713. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  23714. // these are used to calculate buffer length
  23715. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  23716. var indexCount = thetaSegments * phiSegments * 2 * 3;
  23717. // buffers
  23718. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23719. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23720. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23721. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23722. // some helper variables
  23723. var index = 0, indexOffset = 0, segment;
  23724. var radius = innerRadius;
  23725. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23726. var vertex = new Vector3();
  23727. var uv = new Vector2();
  23728. var j, i;
  23729. // generate vertices, normals and uvs
  23730. // values are generate from the inside of the ring to the outside
  23731. for ( j = 0; j <= phiSegments; j ++ ) {
  23732. for ( i = 0; i <= thetaSegments; i ++ ) {
  23733. segment = thetaStart + i / thetaSegments * thetaLength;
  23734. // vertex
  23735. vertex.x = radius * Math.cos( segment );
  23736. vertex.y = radius * Math.sin( segment );
  23737. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23738. // normal
  23739. normals.setXYZ( index, 0, 0, 1 );
  23740. // uv
  23741. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23742. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23743. uvs.setXY( index, uv.x, uv.y );
  23744. // increase index
  23745. index++;
  23746. }
  23747. // increase the radius for next row of vertices
  23748. radius += radiusStep;
  23749. }
  23750. // generate indices
  23751. for ( j = 0; j < phiSegments; j ++ ) {
  23752. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  23753. for ( i = 0; i < thetaSegments; i ++ ) {
  23754. segment = i + thetaSegmentLevel;
  23755. // indices
  23756. var a = segment;
  23757. var b = segment + thetaSegments + 1;
  23758. var c = segment + thetaSegments + 2;
  23759. var d = segment + 1;
  23760. // face one
  23761. indices.setX( indexOffset, a ); indexOffset++;
  23762. indices.setX( indexOffset, b ); indexOffset++;
  23763. indices.setX( indexOffset, c ); indexOffset++;
  23764. // face two
  23765. indices.setX( indexOffset, a ); indexOffset++;
  23766. indices.setX( indexOffset, c ); indexOffset++;
  23767. indices.setX( indexOffset, d ); indexOffset++;
  23768. }
  23769. }
  23770. // build geometry
  23771. this.setIndex( indices );
  23772. this.addAttribute( 'position', vertices );
  23773. this.addAttribute( 'normal', normals );
  23774. this.addAttribute( 'uv', uvs );
  23775. }
  23776. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23777. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  23778. /**
  23779. * @author Kaleb Murphy
  23780. */
  23781. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23782. Geometry.call( this );
  23783. this.type = 'RingGeometry';
  23784. this.parameters = {
  23785. innerRadius: innerRadius,
  23786. outerRadius: outerRadius,
  23787. thetaSegments: thetaSegments,
  23788. phiSegments: phiSegments,
  23789. thetaStart: thetaStart,
  23790. thetaLength: thetaLength
  23791. };
  23792. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  23793. }
  23794. RingGeometry.prototype = Object.create( Geometry.prototype );
  23795. RingGeometry.prototype.constructor = RingGeometry;
  23796. /**
  23797. * @author mrdoob / http://mrdoob.com/
  23798. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  23799. */
  23800. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  23801. Geometry.call( this );
  23802. this.type = 'PlaneGeometry';
  23803. this.parameters = {
  23804. width: width,
  23805. height: height,
  23806. widthSegments: widthSegments,
  23807. heightSegments: heightSegments
  23808. };
  23809. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  23810. }
  23811. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  23812. PlaneGeometry.prototype.constructor = PlaneGeometry;
  23813. /**
  23814. * @author Mugen87 / https://github.com/Mugen87
  23815. */
  23816. // points - to create a closed torus, one must use a set of points
  23817. // like so: [ a, b, c, d, a ], see first is the same as last.
  23818. // segments - the number of circumference segments to create
  23819. // phiStart - the starting radian
  23820. // phiLength - the radian (0 to 2PI) range of the lathed section
  23821. // 2PI is a closed lathe, less than 2PI is a portion.
  23822. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  23823. BufferGeometry.call( this );
  23824. this.type = 'LatheBufferGeometry';
  23825. this.parameters = {
  23826. points: points,
  23827. segments: segments,
  23828. phiStart: phiStart,
  23829. phiLength: phiLength
  23830. };
  23831. segments = Math.floor( segments ) || 12;
  23832. phiStart = phiStart || 0;
  23833. phiLength = phiLength || Math.PI * 2;
  23834. // clamp phiLength so it's in range of [ 0, 2PI ]
  23835. phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 );
  23836. // these are used to calculate buffer length
  23837. var vertexCount = ( segments + 1 ) * points.length;
  23838. var indexCount = segments * points.length * 2 * 3;
  23839. // buffers
  23840. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23841. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23842. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23843. // helper variables
  23844. var index = 0, indexOffset = 0, base;
  23845. var inverseSegments = 1.0 / segments;
  23846. var vertex = new Vector3();
  23847. var uv = new Vector2();
  23848. var i, j;
  23849. // generate vertices and uvs
  23850. for ( i = 0; i <= segments; i ++ ) {
  23851. var phi = phiStart + i * inverseSegments * phiLength;
  23852. var sin = Math.sin( phi );
  23853. var cos = Math.cos( phi );
  23854. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  23855. // vertex
  23856. vertex.x = points[ j ].x * sin;
  23857. vertex.y = points[ j ].y;
  23858. vertex.z = points[ j ].x * cos;
  23859. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23860. // uv
  23861. uv.x = i / segments;
  23862. uv.y = j / ( points.length - 1 );
  23863. uvs.setXY( index, uv.x, uv.y );
  23864. // increase index
  23865. index ++;
  23866. }
  23867. }
  23868. // generate indices
  23869. for ( i = 0; i < segments; i ++ ) {
  23870. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  23871. base = j + i * points.length;
  23872. // indices
  23873. var a = base;
  23874. var b = base + points.length;
  23875. var c = base + points.length + 1;
  23876. var d = base + 1;
  23877. // face one
  23878. indices.setX( indexOffset, a ); indexOffset++;
  23879. indices.setX( indexOffset, b ); indexOffset++;
  23880. indices.setX( indexOffset, d ); indexOffset++;
  23881. // face two
  23882. indices.setX( indexOffset, b ); indexOffset++;
  23883. indices.setX( indexOffset, c ); indexOffset++;
  23884. indices.setX( indexOffset, d ); indexOffset++;
  23885. }
  23886. }
  23887. // build geometry
  23888. this.setIndex( indices );
  23889. this.addAttribute( 'position', vertices );
  23890. this.addAttribute( 'uv', uvs );
  23891. // generate normals
  23892. this.computeVertexNormals();
  23893. // if the geometry is closed, we need to average the normals along the seam.
  23894. // because the corresponding vertices are identical (but still have different UVs).
  23895. if( phiLength === Math.PI * 2 ) {
  23896. var normals = this.attributes.normal.array;
  23897. var n1 = new Vector3();
  23898. var n2 = new Vector3();
  23899. var n = new Vector3();
  23900. // this is the buffer offset for the last line of vertices
  23901. base = segments * points.length * 3;
  23902. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  23903. // select the normal of the vertex in the first line
  23904. n1.x = normals[ j + 0 ];
  23905. n1.y = normals[ j + 1 ];
  23906. n1.z = normals[ j + 2 ];
  23907. // select the normal of the vertex in the last line
  23908. n2.x = normals[ base + j + 0 ];
  23909. n2.y = normals[ base + j + 1 ];
  23910. n2.z = normals[ base + j + 2 ];
  23911. // average normals
  23912. n.addVectors( n1, n2 ).normalize();
  23913. // assign the new values to both normals
  23914. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  23915. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  23916. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  23917. } // next row
  23918. }
  23919. }
  23920. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23921. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  23922. /**
  23923. * @author astrodud / http://astrodud.isgreat.org/
  23924. * @author zz85 / https://github.com/zz85
  23925. * @author bhouston / http://clara.io
  23926. */
  23927. // points - to create a closed torus, one must use a set of points
  23928. // like so: [ a, b, c, d, a ], see first is the same as last.
  23929. // segments - the number of circumference segments to create
  23930. // phiStart - the starting radian
  23931. // phiLength - the radian (0 to 2PI) range of the lathed section
  23932. // 2PI is a closed lathe, less than 2PI is a portion.
  23933. function LatheGeometry( points, segments, phiStart, phiLength ) {
  23934. Geometry.call( this );
  23935. this.type = 'LatheGeometry';
  23936. this.parameters = {
  23937. points: points,
  23938. segments: segments,
  23939. phiStart: phiStart,
  23940. phiLength: phiLength
  23941. };
  23942. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  23943. this.mergeVertices();
  23944. }
  23945. LatheGeometry.prototype = Object.create( Geometry.prototype );
  23946. LatheGeometry.prototype.constructor = LatheGeometry;
  23947. /**
  23948. * @author mrdoob / http://mrdoob.com/
  23949. */
  23950. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23951. Geometry.call( this );
  23952. this.type = 'CylinderGeometry';
  23953. this.parameters = {
  23954. radiusTop: radiusTop,
  23955. radiusBottom: radiusBottom,
  23956. height: height,
  23957. radialSegments: radialSegments,
  23958. heightSegments: heightSegments,
  23959. openEnded: openEnded,
  23960. thetaStart: thetaStart,
  23961. thetaLength: thetaLength
  23962. };
  23963. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  23964. this.mergeVertices();
  23965. }
  23966. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  23967. CylinderGeometry.prototype.constructor = CylinderGeometry;
  23968. /**
  23969. * @author abelnation / http://github.com/abelnation
  23970. */
  23971. function ConeGeometry(
  23972. radius, height,
  23973. radialSegments, heightSegments,
  23974. openEnded, thetaStart, thetaLength ) {
  23975. CylinderGeometry.call( this,
  23976. 0, radius, height,
  23977. radialSegments, heightSegments,
  23978. openEnded, thetaStart, thetaLength );
  23979. this.type = 'ConeGeometry';
  23980. this.parameters = {
  23981. radius: radius,
  23982. height: height,
  23983. radialSegments: radialSegments,
  23984. heightSegments: heightSegments,
  23985. openEnded: openEnded,
  23986. thetaStart: thetaStart,
  23987. thetaLength: thetaLength
  23988. };
  23989. }
  23990. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  23991. ConeGeometry.prototype.constructor = ConeGeometry;
  23992. /*
  23993. * @author: abelnation / http://github.com/abelnation
  23994. */
  23995. function ConeBufferGeometry(
  23996. radius, height,
  23997. radialSegments, heightSegments,
  23998. openEnded, thetaStart, thetaLength ) {
  23999. CylinderBufferGeometry.call( this,
  24000. 0, radius, height,
  24001. radialSegments, heightSegments,
  24002. openEnded, thetaStart, thetaLength );
  24003. this.type = 'ConeBufferGeometry';
  24004. this.parameters = {
  24005. radius: radius,
  24006. height: height,
  24007. radialSegments: radialSegments,
  24008. heightSegments: heightSegments,
  24009. thetaStart: thetaStart,
  24010. thetaLength: thetaLength
  24011. };
  24012. }
  24013. ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24014. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  24015. /**
  24016. * @author benaadams / https://twitter.com/ben_a_adams
  24017. */
  24018. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  24019. BufferGeometry.call( this );
  24020. this.type = 'CircleBufferGeometry';
  24021. this.parameters = {
  24022. radius: radius,
  24023. segments: segments,
  24024. thetaStart: thetaStart,
  24025. thetaLength: thetaLength
  24026. };
  24027. radius = radius || 50;
  24028. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  24029. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24030. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24031. var vertices = segments + 2;
  24032. var positions = new Float32Array( vertices * 3 );
  24033. var normals = new Float32Array( vertices * 3 );
  24034. var uvs = new Float32Array( vertices * 2 );
  24035. // center data is already zero, but need to set a few extras
  24036. normals[ 2 ] = 1.0;
  24037. uvs[ 0 ] = 0.5;
  24038. uvs[ 1 ] = 0.5;
  24039. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  24040. var segment = thetaStart + s / segments * thetaLength;
  24041. positions[ i ] = radius * Math.cos( segment );
  24042. positions[ i + 1 ] = radius * Math.sin( segment );
  24043. normals[ i + 2 ] = 1; // normal z
  24044. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  24045. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  24046. }
  24047. var indices = [];
  24048. for ( var i = 1; i <= segments; i ++ ) {
  24049. indices.push( i, i + 1, 0 );
  24050. }
  24051. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  24052. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24053. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  24054. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  24055. this.boundingSphere = new Sphere( new Vector3(), radius );
  24056. }
  24057. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24058. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  24059. /**
  24060. * @author hughes
  24061. */
  24062. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  24063. Geometry.call( this );
  24064. this.type = 'CircleGeometry';
  24065. this.parameters = {
  24066. radius: radius,
  24067. segments: segments,
  24068. thetaStart: thetaStart,
  24069. thetaLength: thetaLength
  24070. };
  24071. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  24072. }
  24073. CircleGeometry.prototype = Object.create( Geometry.prototype );
  24074. CircleGeometry.prototype.constructor = CircleGeometry;
  24075. /**
  24076. * @author zz85 https://github.com/zz85
  24077. *
  24078. * Centripetal CatmullRom Curve - which is useful for avoiding
  24079. * cusps and self-intersections in non-uniform catmull rom curves.
  24080. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24081. *
  24082. * curve.type accepts centripetal(default), chordal and catmullrom
  24083. * curve.tension is used for catmullrom which defaults to 0.5
  24084. */
  24085. exports.CatmullRomCurve3 = ( function() {
  24086. var
  24087. tmp = new Vector3(),
  24088. px = new CubicPoly(),
  24089. py = new CubicPoly(),
  24090. pz = new CubicPoly();
  24091. /*
  24092. Based on an optimized c++ solution in
  24093. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24094. - http://ideone.com/NoEbVM
  24095. This CubicPoly class could be used for reusing some variables and calculations,
  24096. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24097. which can be placed in CurveUtils.
  24098. */
  24099. function CubicPoly() {
  24100. }
  24101. /*
  24102. * Compute coefficients for a cubic polynomial
  24103. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24104. * such that
  24105. * p(0) = x0, p(1) = x1
  24106. * and
  24107. * p'(0) = t0, p'(1) = t1.
  24108. */
  24109. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24110. this.c0 = x0;
  24111. this.c1 = t0;
  24112. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24113. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24114. };
  24115. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24116. // compute tangents when parameterized in [t1,t2]
  24117. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24118. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24119. // rescale tangents for parametrization in [0,1]
  24120. t1 *= dt1;
  24121. t2 *= dt1;
  24122. // initCubicPoly
  24123. this.init( x1, x2, t1, t2 );
  24124. };
  24125. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24126. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24127. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24128. };
  24129. CubicPoly.prototype.calc = function( t ) {
  24130. var t2 = t * t;
  24131. var t3 = t2 * t;
  24132. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24133. };
  24134. // Subclass Three.js curve
  24135. return Curve.create(
  24136. function ( p /* array of Vector3 */ ) {
  24137. this.points = p || [];
  24138. this.closed = false;
  24139. },
  24140. function ( t ) {
  24141. var points = this.points,
  24142. point, intPoint, weight, l;
  24143. l = points.length;
  24144. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24145. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24146. intPoint = Math.floor( point );
  24147. weight = point - intPoint;
  24148. if ( this.closed ) {
  24149. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24150. } else if ( weight === 0 && intPoint === l - 1 ) {
  24151. intPoint = l - 2;
  24152. weight = 1;
  24153. }
  24154. var p0, p1, p2, p3; // 4 points
  24155. if ( this.closed || intPoint > 0 ) {
  24156. p0 = points[ ( intPoint - 1 ) % l ];
  24157. } else {
  24158. // extrapolate first point
  24159. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24160. p0 = tmp;
  24161. }
  24162. p1 = points[ intPoint % l ];
  24163. p2 = points[ ( intPoint + 1 ) % l ];
  24164. if ( this.closed || intPoint + 2 < l ) {
  24165. p3 = points[ ( intPoint + 2 ) % l ];
  24166. } else {
  24167. // extrapolate last point
  24168. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24169. p3 = tmp;
  24170. }
  24171. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24172. // init Centripetal / Chordal Catmull-Rom
  24173. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24174. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24175. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24176. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24177. // safety check for repeated points
  24178. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24179. if ( dt0 < 1e-4 ) dt0 = dt1;
  24180. if ( dt2 < 1e-4 ) dt2 = dt1;
  24181. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24182. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24183. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24184. } else if ( this.type === 'catmullrom' ) {
  24185. var tension = this.tension !== undefined ? this.tension : 0.5;
  24186. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24187. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24188. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24189. }
  24190. var v = new Vector3(
  24191. px.calc( weight ),
  24192. py.calc( weight ),
  24193. pz.calc( weight )
  24194. );
  24195. return v;
  24196. }
  24197. );
  24198. } )();
  24199. /**************************************************************
  24200. * Closed Spline 3D curve
  24201. **************************************************************/
  24202. function ClosedSplineCurve3( points ) {
  24203. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  24204. exports.CatmullRomCurve3.call( this, points );
  24205. this.type = 'catmullrom';
  24206. this.closed = true;
  24207. }
  24208. ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype );
  24209. /**************************************************************
  24210. * Spline 3D curve
  24211. **************************************************************/
  24212. var SplineCurve3 = Curve.create(
  24213. function ( points /* array of Vector3 */ ) {
  24214. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24215. this.points = ( points === undefined ) ? [] : points;
  24216. },
  24217. function ( t ) {
  24218. var points = this.points;
  24219. var point = ( points.length - 1 ) * t;
  24220. var intPoint = Math.floor( point );
  24221. var weight = point - intPoint;
  24222. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24223. var point1 = points[ intPoint ];
  24224. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24225. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24226. var interpolate = exports.CurveUtils.interpolate;
  24227. return new Vector3(
  24228. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24229. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24230. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24231. );
  24232. }
  24233. );
  24234. /**************************************************************
  24235. * Cubic Bezier 3D curve
  24236. **************************************************************/
  24237. exports.CubicBezierCurve3 = Curve.create(
  24238. function ( v0, v1, v2, v3 ) {
  24239. this.v0 = v0;
  24240. this.v1 = v1;
  24241. this.v2 = v2;
  24242. this.v3 = v3;
  24243. },
  24244. function ( t ) {
  24245. var b3 = exports.ShapeUtils.b3;
  24246. return new Vector3(
  24247. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24248. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24249. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24250. );
  24251. }
  24252. );
  24253. /**************************************************************
  24254. * Quadratic Bezier 3D curve
  24255. **************************************************************/
  24256. exports.QuadraticBezierCurve3 = Curve.create(
  24257. function ( v0, v1, v2 ) {
  24258. this.v0 = v0;
  24259. this.v1 = v1;
  24260. this.v2 = v2;
  24261. },
  24262. function ( t ) {
  24263. var b2 = exports.ShapeUtils.b2;
  24264. return new Vector3(
  24265. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24266. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24267. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24268. );
  24269. }
  24270. );
  24271. /**************************************************************
  24272. * Line3D
  24273. **************************************************************/
  24274. exports.LineCurve3 = Curve.create(
  24275. function ( v1, v2 ) {
  24276. this.v1 = v1;
  24277. this.v2 = v2;
  24278. },
  24279. function ( t ) {
  24280. if ( t === 1 ) {
  24281. return this.v2.clone();
  24282. }
  24283. var vector = new Vector3();
  24284. vector.subVectors( this.v2, this.v1 ); // diff
  24285. vector.multiplyScalar( t );
  24286. vector.add( this.v1 );
  24287. return vector;
  24288. }
  24289. );
  24290. /**************************************************************
  24291. * Arc curve
  24292. **************************************************************/
  24293. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24294. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24295. }
  24296. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24297. ArcCurve.prototype.constructor = ArcCurve;
  24298. /**
  24299. * @author alteredq / http://alteredqualia.com/
  24300. */
  24301. exports.SceneUtils = {
  24302. createMultiMaterialObject: function ( geometry, materials ) {
  24303. var group = new Group();
  24304. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24305. group.add( new Mesh( geometry, materials[ i ] ) );
  24306. }
  24307. return group;
  24308. },
  24309. detach: function ( child, parent, scene ) {
  24310. child.applyMatrix( parent.matrixWorld );
  24311. parent.remove( child );
  24312. scene.add( child );
  24313. },
  24314. attach: function ( child, scene, parent ) {
  24315. var matrixWorldInverse = new Matrix4();
  24316. matrixWorldInverse.getInverse( parent.matrixWorld );
  24317. child.applyMatrix( matrixWorldInverse );
  24318. scene.remove( child );
  24319. parent.add( child );
  24320. }
  24321. };
  24322. function Face4 ( a, b, c, d, normal, color, materialIndex ) {
  24323. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24324. return new Face3( a, b, c, normal, color, materialIndex );
  24325. }
  24326. var LineStrip = 0;
  24327. var LinePieces = 1;
  24328. function PointCloud ( geometry, material ) {
  24329. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24330. return new Points( geometry, material );
  24331. }
  24332. function ParticleSystem ( geometry, material ) {
  24333. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24334. return new Points( geometry, material );
  24335. }
  24336. function PointCloudMaterial ( parameters ) {
  24337. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24338. return new PointsMaterial( parameters );
  24339. }
  24340. function ParticleBasicMaterial ( parameters ) {
  24341. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24342. return new PointsMaterial( parameters );
  24343. }
  24344. function ParticleSystemMaterial ( parameters ) {
  24345. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24346. return new PointsMaterial( parameters );
  24347. }
  24348. function Vertex ( x, y, z ) {
  24349. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24350. return new Vector3( x, y, z );
  24351. }
  24352. //
  24353. Object.assign( Box2.prototype, {
  24354. empty: function () {
  24355. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  24356. return this.isEmpty();
  24357. },
  24358. isIntersectionBox: function ( box ) {
  24359. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24360. return this.intersectsBox( box );
  24361. }
  24362. } );
  24363. Object.assign( Box3.prototype, {
  24364. empty: function () {
  24365. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  24366. return this.isEmpty();
  24367. },
  24368. isIntersectionBox: function ( box ) {
  24369. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24370. return this.intersectsBox( box );
  24371. },
  24372. isIntersectionSphere: function ( sphere ) {
  24373. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24374. return this.intersectsSphere( sphere );
  24375. }
  24376. } );
  24377. Object.assign( Matrix3.prototype, {
  24378. multiplyVector3: function ( vector ) {
  24379. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  24380. return vector.applyMatrix3( this );
  24381. },
  24382. multiplyVector3Array: function ( a ) {
  24383. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24384. return this.applyToVector3Array( a );
  24385. }
  24386. } );
  24387. Object.assign( Matrix4.prototype, {
  24388. extractPosition: function ( m ) {
  24389. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  24390. return this.copyPosition( m );
  24391. },
  24392. setRotationFromQuaternion: function ( q ) {
  24393. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  24394. return this.makeRotationFromQuaternion( q );
  24395. },
  24396. multiplyVector3: function ( vector ) {
  24397. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  24398. return vector.applyProjection( this );
  24399. },
  24400. multiplyVector4: function ( vector ) {
  24401. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24402. return vector.applyMatrix4( this );
  24403. },
  24404. multiplyVector3Array: function ( a ) {
  24405. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24406. return this.applyToVector3Array( a );
  24407. },
  24408. rotateAxis: function ( v ) {
  24409. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  24410. v.transformDirection( this );
  24411. },
  24412. crossVector: function ( vector ) {
  24413. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24414. return vector.applyMatrix4( this );
  24415. },
  24416. translate: function ( v ) {
  24417. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  24418. },
  24419. rotateX: function ( angle ) {
  24420. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  24421. },
  24422. rotateY: function ( angle ) {
  24423. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  24424. },
  24425. rotateZ: function ( angle ) {
  24426. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  24427. },
  24428. rotateByAxis: function ( axis, angle ) {
  24429. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  24430. }
  24431. } );
  24432. Object.assign( Plane.prototype, {
  24433. isIntersectionLine: function ( line ) {
  24434. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  24435. return this.intersectsLine( line );
  24436. }
  24437. } );
  24438. Object.assign( Quaternion.prototype, {
  24439. multiplyVector3: function ( vector ) {
  24440. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  24441. return vector.applyQuaternion( this );
  24442. }
  24443. } );
  24444. Object.assign( Ray.prototype, {
  24445. isIntersectionBox: function ( box ) {
  24446. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24447. return this.intersectsBox( box );
  24448. },
  24449. isIntersectionPlane: function ( plane ) {
  24450. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  24451. return this.intersectsPlane( plane );
  24452. },
  24453. isIntersectionSphere: function ( sphere ) {
  24454. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24455. return this.intersectsSphere( sphere );
  24456. }
  24457. } );
  24458. Object.assign( Vector3.prototype, {
  24459. setEulerFromRotationMatrix: function () {
  24460. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  24461. },
  24462. setEulerFromQuaternion: function () {
  24463. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  24464. },
  24465. getPositionFromMatrix: function ( m ) {
  24466. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  24467. return this.setFromMatrixPosition( m );
  24468. },
  24469. getScaleFromMatrix: function ( m ) {
  24470. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  24471. return this.setFromMatrixScale( m );
  24472. },
  24473. getColumnFromMatrix: function ( index, matrix ) {
  24474. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  24475. return this.setFromMatrixColumn( matrix, index );
  24476. }
  24477. } );
  24478. //
  24479. Object.assign( Object3D.prototype, {
  24480. getChildByName: function ( name ) {
  24481. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  24482. return this.getObjectByName( name );
  24483. },
  24484. renderDepth: function ( value ) {
  24485. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  24486. },
  24487. translate: function ( distance, axis ) {
  24488. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  24489. return this.translateOnAxis( axis, distance );
  24490. }
  24491. } );
  24492. Object.defineProperties( Object3D.prototype, {
  24493. eulerOrder: {
  24494. get: function () {
  24495. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24496. return this.rotation.order;
  24497. },
  24498. set: function ( value ) {
  24499. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24500. this.rotation.order = value;
  24501. }
  24502. },
  24503. useQuaternion: {
  24504. get: function () {
  24505. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24506. },
  24507. set: function ( value ) {
  24508. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24509. }
  24510. }
  24511. } );
  24512. Object.defineProperties( LOD.prototype, {
  24513. objects: {
  24514. get: function () {
  24515. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  24516. return this.levels;
  24517. }
  24518. }
  24519. } );
  24520. //
  24521. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  24522. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  24523. "Use .setFocalLength and .filmGauge for a photographic setup." );
  24524. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  24525. this.setFocalLength( focalLength );
  24526. };
  24527. //
  24528. Object.defineProperties( Light.prototype, {
  24529. onlyShadow: {
  24530. set: function ( value ) {
  24531. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  24532. }
  24533. },
  24534. shadowCameraFov: {
  24535. set: function ( value ) {
  24536. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  24537. this.shadow.camera.fov = value;
  24538. }
  24539. },
  24540. shadowCameraLeft: {
  24541. set: function ( value ) {
  24542. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  24543. this.shadow.camera.left = value;
  24544. }
  24545. },
  24546. shadowCameraRight: {
  24547. set: function ( value ) {
  24548. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  24549. this.shadow.camera.right = value;
  24550. }
  24551. },
  24552. shadowCameraTop: {
  24553. set: function ( value ) {
  24554. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  24555. this.shadow.camera.top = value;
  24556. }
  24557. },
  24558. shadowCameraBottom: {
  24559. set: function ( value ) {
  24560. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  24561. this.shadow.camera.bottom = value;
  24562. }
  24563. },
  24564. shadowCameraNear: {
  24565. set: function ( value ) {
  24566. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  24567. this.shadow.camera.near = value;
  24568. }
  24569. },
  24570. shadowCameraFar: {
  24571. set: function ( value ) {
  24572. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  24573. this.shadow.camera.far = value;
  24574. }
  24575. },
  24576. shadowCameraVisible: {
  24577. set: function ( value ) {
  24578. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  24579. }
  24580. },
  24581. shadowBias: {
  24582. set: function ( value ) {
  24583. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  24584. this.shadow.bias = value;
  24585. }
  24586. },
  24587. shadowDarkness: {
  24588. set: function ( value ) {
  24589. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  24590. }
  24591. },
  24592. shadowMapWidth: {
  24593. set: function ( value ) {
  24594. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  24595. this.shadow.mapSize.width = value;
  24596. }
  24597. },
  24598. shadowMapHeight: {
  24599. set: function ( value ) {
  24600. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  24601. this.shadow.mapSize.height = value;
  24602. }
  24603. }
  24604. } );
  24605. //
  24606. Object.defineProperties( BufferAttribute.prototype, {
  24607. length: {
  24608. get: function () {
  24609. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  24610. return this.array.length;
  24611. }
  24612. }
  24613. } );
  24614. Object.assign( BufferGeometry.prototype, {
  24615. addIndex: function ( index ) {
  24616. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  24617. this.setIndex( index );
  24618. },
  24619. addDrawCall: function ( start, count, indexOffset ) {
  24620. if ( indexOffset !== undefined ) {
  24621. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  24622. }
  24623. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  24624. this.addGroup( start, count );
  24625. },
  24626. clearDrawCalls: function () {
  24627. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  24628. this.clearGroups();
  24629. },
  24630. computeTangents: function () {
  24631. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  24632. },
  24633. computeOffsets: function () {
  24634. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  24635. }
  24636. } );
  24637. Object.defineProperties( BufferGeometry.prototype, {
  24638. drawcalls: {
  24639. get: function () {
  24640. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  24641. return this.groups;
  24642. }
  24643. },
  24644. offsets: {
  24645. get: function () {
  24646. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  24647. return this.groups;
  24648. }
  24649. }
  24650. } );
  24651. //
  24652. Object.defineProperties( Material.prototype, {
  24653. wrapAround: {
  24654. get: function () {
  24655. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24656. },
  24657. set: function ( value ) {
  24658. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24659. }
  24660. },
  24661. wrapRGB: {
  24662. get: function () {
  24663. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  24664. return new Color();
  24665. }
  24666. }
  24667. } );
  24668. Object.defineProperties( MeshPhongMaterial.prototype, {
  24669. metal: {
  24670. get: function () {
  24671. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  24672. return false;
  24673. },
  24674. set: function ( value ) {
  24675. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  24676. }
  24677. }
  24678. } );
  24679. Object.defineProperties( ShaderMaterial.prototype, {
  24680. derivatives: {
  24681. get: function () {
  24682. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24683. return this.extensions.derivatives;
  24684. },
  24685. set: function ( value ) {
  24686. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24687. this.extensions.derivatives = value;
  24688. }
  24689. }
  24690. } );
  24691. //
  24692. EventDispatcher.prototype = Object.assign( Object.create( {
  24693. // Note: Extra base ensures these properties are not 'assign'ed.
  24694. constructor: EventDispatcher,
  24695. apply: function ( target ) {
  24696. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  24697. "just inherit or Object.assign the prototype to mix-in." );
  24698. Object.assign( target, this );
  24699. }
  24700. } ), EventDispatcher.prototype );
  24701. //
  24702. Object.assign( WebGLRenderer.prototype, {
  24703. supportsFloatTextures: function () {
  24704. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  24705. return this.extensions.get( 'OES_texture_float' );
  24706. },
  24707. supportsHalfFloatTextures: function () {
  24708. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  24709. return this.extensions.get( 'OES_texture_half_float' );
  24710. },
  24711. supportsStandardDerivatives: function () {
  24712. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  24713. return this.extensions.get( 'OES_standard_derivatives' );
  24714. },
  24715. supportsCompressedTextureS3TC: function () {
  24716. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  24717. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24718. },
  24719. supportsCompressedTexturePVRTC: function () {
  24720. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  24721. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24722. },
  24723. supportsBlendMinMax: function () {
  24724. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  24725. return this.extensions.get( 'EXT_blend_minmax' );
  24726. },
  24727. supportsVertexTextures: function () {
  24728. return this.capabilities.vertexTextures;
  24729. },
  24730. supportsInstancedArrays: function () {
  24731. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  24732. return this.extensions.get( 'ANGLE_instanced_arrays' );
  24733. },
  24734. enableScissorTest: function ( boolean ) {
  24735. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  24736. this.setScissorTest( boolean );
  24737. },
  24738. initMaterial: function () {
  24739. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  24740. },
  24741. addPrePlugin: function () {
  24742. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  24743. },
  24744. addPostPlugin: function () {
  24745. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  24746. },
  24747. updateShadowMap: function () {
  24748. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  24749. }
  24750. } );
  24751. Object.defineProperties( WebGLRenderer.prototype, {
  24752. shadowMapEnabled: {
  24753. get: function () {
  24754. return this.shadowMap.enabled;
  24755. },
  24756. set: function ( value ) {
  24757. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  24758. this.shadowMap.enabled = value;
  24759. }
  24760. },
  24761. shadowMapType: {
  24762. get: function () {
  24763. return this.shadowMap.type;
  24764. },
  24765. set: function ( value ) {
  24766. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  24767. this.shadowMap.type = value;
  24768. }
  24769. },
  24770. shadowMapCullFace: {
  24771. get: function () {
  24772. return this.shadowMap.cullFace;
  24773. },
  24774. set: function ( value ) {
  24775. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  24776. this.shadowMap.cullFace = value;
  24777. }
  24778. }
  24779. } );
  24780. Object.defineProperties( WebGLShadowMap.prototype, {
  24781. cullFace: {
  24782. get: function () {
  24783. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  24784. },
  24785. set: function ( cullFace ) {
  24786. var value = ( cullFace !== CullFaceBack );
  24787. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  24788. this.renderReverseSided = value;
  24789. }
  24790. }
  24791. } );
  24792. //
  24793. Object.defineProperties( WebGLRenderTarget.prototype, {
  24794. wrapS: {
  24795. get: function () {
  24796. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24797. return this.texture.wrapS;
  24798. },
  24799. set: function ( value ) {
  24800. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24801. this.texture.wrapS = value;
  24802. }
  24803. },
  24804. wrapT: {
  24805. get: function () {
  24806. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24807. return this.texture.wrapT;
  24808. },
  24809. set: function ( value ) {
  24810. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24811. this.texture.wrapT = value;
  24812. }
  24813. },
  24814. magFilter: {
  24815. get: function () {
  24816. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24817. return this.texture.magFilter;
  24818. },
  24819. set: function ( value ) {
  24820. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24821. this.texture.magFilter = value;
  24822. }
  24823. },
  24824. minFilter: {
  24825. get: function () {
  24826. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24827. return this.texture.minFilter;
  24828. },
  24829. set: function ( value ) {
  24830. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24831. this.texture.minFilter = value;
  24832. }
  24833. },
  24834. anisotropy: {
  24835. get: function () {
  24836. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24837. return this.texture.anisotropy;
  24838. },
  24839. set: function ( value ) {
  24840. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24841. this.texture.anisotropy = value;
  24842. }
  24843. },
  24844. offset: {
  24845. get: function () {
  24846. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24847. return this.texture.offset;
  24848. },
  24849. set: function ( value ) {
  24850. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24851. this.texture.offset = value;
  24852. }
  24853. },
  24854. repeat: {
  24855. get: function () {
  24856. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24857. return this.texture.repeat;
  24858. },
  24859. set: function ( value ) {
  24860. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24861. this.texture.repeat = value;
  24862. }
  24863. },
  24864. format: {
  24865. get: function () {
  24866. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24867. return this.texture.format;
  24868. },
  24869. set: function ( value ) {
  24870. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24871. this.texture.format = value;
  24872. }
  24873. },
  24874. type: {
  24875. get: function () {
  24876. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24877. return this.texture.type;
  24878. },
  24879. set: function ( value ) {
  24880. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24881. this.texture.type = value;
  24882. }
  24883. },
  24884. generateMipmaps: {
  24885. get: function () {
  24886. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24887. return this.texture.generateMipmaps;
  24888. },
  24889. set: function ( value ) {
  24890. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24891. this.texture.generateMipmaps = value;
  24892. }
  24893. }
  24894. } );
  24895. //
  24896. Object.assign( Audio.prototype, {
  24897. load: function ( file ) {
  24898. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  24899. var scope = this;
  24900. var audioLoader = new AudioLoader();
  24901. audioLoader.load( file, function ( buffer ) {
  24902. scope.setBuffer( buffer );
  24903. } );
  24904. return this;
  24905. }
  24906. } );
  24907. Object.assign( AudioAnalyser.prototype, {
  24908. getData: function ( file ) {
  24909. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  24910. return this.getFrequencyData();
  24911. }
  24912. } );
  24913. //
  24914. var GeometryUtils = {
  24915. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  24916. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  24917. var matrix;
  24918. if ( geometry2.isMesh ) {
  24919. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  24920. matrix = geometry2.matrix;
  24921. geometry2 = geometry2.geometry;
  24922. }
  24923. geometry1.merge( geometry2, matrix, materialIndexOffset );
  24924. },
  24925. center: function ( geometry ) {
  24926. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  24927. return geometry.center();
  24928. }
  24929. };
  24930. var ImageUtils = {
  24931. crossOrigin: undefined,
  24932. loadTexture: function ( url, mapping, onLoad, onError ) {
  24933. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  24934. var loader = new TextureLoader();
  24935. loader.setCrossOrigin( this.crossOrigin );
  24936. var texture = loader.load( url, onLoad, undefined, onError );
  24937. if ( mapping ) texture.mapping = mapping;
  24938. return texture;
  24939. },
  24940. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  24941. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  24942. var loader = new CubeTextureLoader();
  24943. loader.setCrossOrigin( this.crossOrigin );
  24944. var texture = loader.load( urls, onLoad, undefined, onError );
  24945. if ( mapping ) texture.mapping = mapping;
  24946. return texture;
  24947. },
  24948. loadCompressedTexture: function () {
  24949. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  24950. },
  24951. loadCompressedTextureCube: function () {
  24952. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  24953. }
  24954. };
  24955. //
  24956. function Projector () {
  24957. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  24958. this.projectVector = function ( vector, camera ) {
  24959. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  24960. vector.project( camera );
  24961. };
  24962. this.unprojectVector = function ( vector, camera ) {
  24963. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  24964. vector.unproject( camera );
  24965. };
  24966. this.pickingRay = function ( vector, camera ) {
  24967. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  24968. };
  24969. }
  24970. //
  24971. function CanvasRenderer () {
  24972. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  24973. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  24974. this.clear = function () {};
  24975. this.render = function () {};
  24976. this.setClearColor = function () {};
  24977. this.setSize = function () {};
  24978. }
  24979. Object.defineProperty( exports, 'AudioContext', {
  24980. get: function () {
  24981. return exports.getAudioContext();
  24982. }
  24983. });
  24984. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  24985. exports.WebGLRenderTarget = WebGLRenderTarget;
  24986. exports.WebGLRenderer = WebGLRenderer;
  24987. exports.ShaderLib = ShaderLib;
  24988. exports.UniformsLib = UniformsLib;
  24989. exports.ShaderChunk = ShaderChunk;
  24990. exports.FogExp2 = FogExp2;
  24991. exports.Fog = Fog;
  24992. exports.Scene = Scene;
  24993. exports.LensFlare = LensFlare;
  24994. exports.Sprite = Sprite;
  24995. exports.LOD = LOD;
  24996. exports.SkinnedMesh = SkinnedMesh;
  24997. exports.Skeleton = Skeleton;
  24998. exports.Bone = Bone;
  24999. exports.Mesh = Mesh;
  25000. exports.LineSegments = LineSegments;
  25001. exports.Line = Line;
  25002. exports.Points = Points;
  25003. exports.Group = Group;
  25004. exports.VideoTexture = VideoTexture;
  25005. exports.DataTexture = DataTexture;
  25006. exports.CompressedTexture = CompressedTexture;
  25007. exports.CubeTexture = CubeTexture;
  25008. exports.CanvasTexture = CanvasTexture;
  25009. exports.DepthTexture = DepthTexture;
  25010. exports.TextureIdCount = TextureIdCount;
  25011. exports.Texture = Texture;
  25012. exports.ShadowMaterial = ShadowMaterial;
  25013. exports.SpriteMaterial = SpriteMaterial;
  25014. exports.RawShaderMaterial = RawShaderMaterial;
  25015. exports.ShaderMaterial = ShaderMaterial;
  25016. exports.PointsMaterial = PointsMaterial;
  25017. exports.MultiMaterial = MultiMaterial;
  25018. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  25019. exports.MeshStandardMaterial = MeshStandardMaterial;
  25020. exports.MeshPhongMaterial = MeshPhongMaterial;
  25021. exports.MeshNormalMaterial = MeshNormalMaterial;
  25022. exports.MeshLambertMaterial = MeshLambertMaterial;
  25023. exports.MeshDepthMaterial = MeshDepthMaterial;
  25024. exports.MeshBasicMaterial = MeshBasicMaterial;
  25025. exports.LineDashedMaterial = LineDashedMaterial;
  25026. exports.LineBasicMaterial = LineBasicMaterial;
  25027. exports.MaterialIdCount = MaterialIdCount;
  25028. exports.Material = Material;
  25029. exports.CompressedTextureLoader = CompressedTextureLoader;
  25030. exports.BinaryTextureLoader = BinaryTextureLoader;
  25031. exports.DataTextureLoader = DataTextureLoader;
  25032. exports.CubeTextureLoader = CubeTextureLoader;
  25033. exports.TextureLoader = TextureLoader;
  25034. exports.ObjectLoader = ObjectLoader;
  25035. exports.MaterialLoader = MaterialLoader;
  25036. exports.BufferGeometryLoader = BufferGeometryLoader;
  25037. exports.LoadingManager = LoadingManager;
  25038. exports.JSONLoader = JSONLoader;
  25039. exports.ImageLoader = ImageLoader;
  25040. exports.FontLoader = FontLoader;
  25041. exports.XHRLoader = XHRLoader;
  25042. exports.Loader = Loader;
  25043. exports.AudioLoader = AudioLoader;
  25044. exports.SpotLightShadow = SpotLightShadow;
  25045. exports.SpotLight = SpotLight;
  25046. exports.PointLight = PointLight;
  25047. exports.HemisphereLight = HemisphereLight;
  25048. exports.DirectionalLightShadow = DirectionalLightShadow;
  25049. exports.DirectionalLight = DirectionalLight;
  25050. exports.AmbientLight = AmbientLight;
  25051. exports.LightShadow = LightShadow;
  25052. exports.Light = Light;
  25053. exports.StereoCamera = StereoCamera;
  25054. exports.PerspectiveCamera = PerspectiveCamera;
  25055. exports.OrthographicCamera = OrthographicCamera;
  25056. exports.CubeCamera = CubeCamera;
  25057. exports.Camera = Camera;
  25058. exports.AudioListener = AudioListener;
  25059. exports.PositionalAudio = PositionalAudio;
  25060. exports.getAudioContext = getAudioContext;
  25061. exports.AudioAnalyser = AudioAnalyser;
  25062. exports.Audio = Audio;
  25063. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25064. exports.StringKeyframeTrack = StringKeyframeTrack;
  25065. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25066. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25067. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25068. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25069. exports.PropertyMixer = PropertyMixer;
  25070. exports.PropertyBinding = PropertyBinding;
  25071. exports.KeyframeTrack = KeyframeTrack;
  25072. exports.AnimationObjectGroup = AnimationObjectGroup;
  25073. exports.AnimationMixer = AnimationMixer;
  25074. exports.AnimationClip = AnimationClip;
  25075. exports.Uniform = Uniform;
  25076. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25077. exports.BufferGeometry = BufferGeometry;
  25078. exports.DirectGeometry = DirectGeometry;
  25079. exports.GeometryIdCount = GeometryIdCount;
  25080. exports.Geometry = Geometry;
  25081. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25082. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25083. exports.InterleavedBuffer = InterleavedBuffer;
  25084. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25085. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  25086. exports.Float64Attribute = Float64Attribute;
  25087. exports.Float32Attribute = Float32Attribute;
  25088. exports.Uint32Attribute = Uint32Attribute;
  25089. exports.Int32Attribute = Int32Attribute;
  25090. exports.Uint16Attribute = Uint16Attribute;
  25091. exports.Int16Attribute = Int16Attribute;
  25092. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  25093. exports.Uint8Attribute = Uint8Attribute;
  25094. exports.Int8Attribute = Int8Attribute;
  25095. exports.BufferAttribute = BufferAttribute;
  25096. exports.Face3 = Face3;
  25097. exports.Object3DIdCount = Object3DIdCount;
  25098. exports.Object3D = Object3D;
  25099. exports.Raycaster = Raycaster;
  25100. exports.Layers = Layers;
  25101. exports.EventDispatcher = EventDispatcher;
  25102. exports.Clock = Clock;
  25103. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25104. exports.LinearInterpolant = LinearInterpolant;
  25105. exports.DiscreteInterpolant = DiscreteInterpolant;
  25106. exports.CubicInterpolant = CubicInterpolant;
  25107. exports.Interpolant = Interpolant;
  25108. exports.Triangle = Triangle;
  25109. exports.Spline = Spline;
  25110. exports.Spherical = Spherical;
  25111. exports.Plane = Plane;
  25112. exports.Frustum = Frustum;
  25113. exports.Sphere = Sphere;
  25114. exports.Ray = Ray;
  25115. exports.Matrix4 = Matrix4;
  25116. exports.Matrix3 = Matrix3;
  25117. exports.Box3 = Box3;
  25118. exports.Box2 = Box2;
  25119. exports.Line3 = Line3;
  25120. exports.Euler = Euler;
  25121. exports.Vector4 = Vector4;
  25122. exports.Vector3 = Vector3;
  25123. exports.Vector2 = Vector2;
  25124. exports.Quaternion = Quaternion;
  25125. exports.Color = Color;
  25126. exports.MorphBlendMesh = MorphBlendMesh;
  25127. exports.ImmediateRenderObject = ImmediateRenderObject;
  25128. exports.WireframeHelper = WireframeHelper;
  25129. exports.VertexNormalsHelper = VertexNormalsHelper;
  25130. exports.SpotLightHelper = SpotLightHelper;
  25131. exports.SkeletonHelper = SkeletonHelper;
  25132. exports.PointLightHelper = PointLightHelper;
  25133. exports.HemisphereLightHelper = HemisphereLightHelper;
  25134. exports.GridHelper = GridHelper;
  25135. exports.FaceNormalsHelper = FaceNormalsHelper;
  25136. exports.EdgesHelper = EdgesHelper;
  25137. exports.DirectionalLightHelper = DirectionalLightHelper;
  25138. exports.CameraHelper = CameraHelper;
  25139. exports.BoundingBoxHelper = BoundingBoxHelper;
  25140. exports.BoxHelper = BoxHelper;
  25141. exports.ArrowHelper = ArrowHelper;
  25142. exports.AxisHelper = AxisHelper;
  25143. exports.WireframeGeometry = WireframeGeometry;
  25144. exports.ParametricGeometry = ParametricGeometry;
  25145. exports.TetrahedronGeometry = TetrahedronGeometry;
  25146. exports.OctahedronGeometry = OctahedronGeometry;
  25147. exports.IcosahedronGeometry = IcosahedronGeometry;
  25148. exports.DodecahedronGeometry = DodecahedronGeometry;
  25149. exports.PolyhedronGeometry = PolyhedronGeometry;
  25150. exports.TubeGeometry = TubeGeometry;
  25151. exports.TorusKnotGeometry = TorusKnotGeometry;
  25152. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  25153. exports.TorusGeometry = TorusGeometry;
  25154. exports.TorusBufferGeometry = TorusBufferGeometry;
  25155. exports.TextGeometry = TextGeometry;
  25156. exports.SphereBufferGeometry = SphereBufferGeometry;
  25157. exports.SphereGeometry = SphereGeometry;
  25158. exports.RingGeometry = RingGeometry;
  25159. exports.RingBufferGeometry = RingBufferGeometry;
  25160. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  25161. exports.PlaneGeometry = PlaneGeometry;
  25162. exports.LatheGeometry = LatheGeometry;
  25163. exports.LatheBufferGeometry = LatheBufferGeometry;
  25164. exports.ShapeGeometry = ShapeGeometry;
  25165. exports.ExtrudeGeometry = ExtrudeGeometry;
  25166. exports.EdgesGeometry = EdgesGeometry;
  25167. exports.ConeGeometry = ConeGeometry;
  25168. exports.ConeBufferGeometry = ConeBufferGeometry;
  25169. exports.CylinderGeometry = CylinderGeometry;
  25170. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  25171. exports.CircleBufferGeometry = CircleBufferGeometry;
  25172. exports.CircleGeometry = CircleGeometry;
  25173. exports.BoxBufferGeometry = BoxBufferGeometry;
  25174. exports.BoxGeometry = BoxGeometry;
  25175. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  25176. exports.SplineCurve3 = SplineCurve3;
  25177. exports.ArcCurve = ArcCurve;
  25178. exports.EllipseCurve = EllipseCurve;
  25179. exports.SplineCurve = SplineCurve;
  25180. exports.CubicBezierCurve = CubicBezierCurve;
  25181. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25182. exports.LineCurve = LineCurve;
  25183. exports.Shape = Shape;
  25184. exports.ShapePath = ShapePath;
  25185. exports.Path = Path;
  25186. exports.Font = Font;
  25187. exports.CurvePath = CurvePath;
  25188. exports.Curve = Curve;
  25189. exports.REVISION = REVISION;
  25190. exports.MOUSE = MOUSE;
  25191. exports.CullFaceNone = CullFaceNone;
  25192. exports.CullFaceBack = CullFaceBack;
  25193. exports.CullFaceFront = CullFaceFront;
  25194. exports.CullFaceFrontBack = CullFaceFrontBack;
  25195. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  25196. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  25197. exports.BasicShadowMap = BasicShadowMap;
  25198. exports.PCFShadowMap = PCFShadowMap;
  25199. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  25200. exports.FrontSide = FrontSide;
  25201. exports.BackSide = BackSide;
  25202. exports.DoubleSide = DoubleSide;
  25203. exports.FlatShading = FlatShading;
  25204. exports.SmoothShading = SmoothShading;
  25205. exports.NoColors = NoColors;
  25206. exports.FaceColors = FaceColors;
  25207. exports.VertexColors = VertexColors;
  25208. exports.NoBlending = NoBlending;
  25209. exports.NormalBlending = NormalBlending;
  25210. exports.AdditiveBlending = AdditiveBlending;
  25211. exports.SubtractiveBlending = SubtractiveBlending;
  25212. exports.MultiplyBlending = MultiplyBlending;
  25213. exports.CustomBlending = CustomBlending;
  25214. exports.AddEquation = AddEquation;
  25215. exports.SubtractEquation = SubtractEquation;
  25216. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  25217. exports.MinEquation = MinEquation;
  25218. exports.MaxEquation = MaxEquation;
  25219. exports.ZeroFactor = ZeroFactor;
  25220. exports.OneFactor = OneFactor;
  25221. exports.SrcColorFactor = SrcColorFactor;
  25222. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  25223. exports.SrcAlphaFactor = SrcAlphaFactor;
  25224. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  25225. exports.DstAlphaFactor = DstAlphaFactor;
  25226. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  25227. exports.DstColorFactor = DstColorFactor;
  25228. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  25229. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  25230. exports.NeverDepth = NeverDepth;
  25231. exports.AlwaysDepth = AlwaysDepth;
  25232. exports.LessDepth = LessDepth;
  25233. exports.LessEqualDepth = LessEqualDepth;
  25234. exports.EqualDepth = EqualDepth;
  25235. exports.GreaterEqualDepth = GreaterEqualDepth;
  25236. exports.GreaterDepth = GreaterDepth;
  25237. exports.NotEqualDepth = NotEqualDepth;
  25238. exports.MultiplyOperation = MultiplyOperation;
  25239. exports.MixOperation = MixOperation;
  25240. exports.AddOperation = AddOperation;
  25241. exports.NoToneMapping = NoToneMapping;
  25242. exports.LinearToneMapping = LinearToneMapping;
  25243. exports.ReinhardToneMapping = ReinhardToneMapping;
  25244. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  25245. exports.CineonToneMapping = CineonToneMapping;
  25246. exports.UVMapping = UVMapping;
  25247. exports.CubeReflectionMapping = CubeReflectionMapping;
  25248. exports.CubeRefractionMapping = CubeRefractionMapping;
  25249. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  25250. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  25251. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  25252. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  25253. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  25254. exports.RepeatWrapping = RepeatWrapping;
  25255. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  25256. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  25257. exports.NearestFilter = NearestFilter;
  25258. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  25259. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  25260. exports.LinearFilter = LinearFilter;
  25261. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  25262. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  25263. exports.UnsignedByteType = UnsignedByteType;
  25264. exports.ByteType = ByteType;
  25265. exports.ShortType = ShortType;
  25266. exports.UnsignedShortType = UnsignedShortType;
  25267. exports.IntType = IntType;
  25268. exports.UnsignedIntType = UnsignedIntType;
  25269. exports.FloatType = FloatType;
  25270. exports.HalfFloatType = HalfFloatType;
  25271. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  25272. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  25273. exports.UnsignedShort565Type = UnsignedShort565Type;
  25274. exports.UnsignedInt248Type = UnsignedInt248Type;
  25275. exports.AlphaFormat = AlphaFormat;
  25276. exports.RGBFormat = RGBFormat;
  25277. exports.RGBAFormat = RGBAFormat;
  25278. exports.LuminanceFormat = LuminanceFormat;
  25279. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  25280. exports.RGBEFormat = RGBEFormat;
  25281. exports.DepthFormat = DepthFormat;
  25282. exports.DepthStencilFormat = DepthStencilFormat;
  25283. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  25284. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  25285. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  25286. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  25287. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  25288. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  25289. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  25290. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  25291. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  25292. exports.LoopOnce = LoopOnce;
  25293. exports.LoopRepeat = LoopRepeat;
  25294. exports.LoopPingPong = LoopPingPong;
  25295. exports.InterpolateDiscrete = InterpolateDiscrete;
  25296. exports.InterpolateLinear = InterpolateLinear;
  25297. exports.InterpolateSmooth = InterpolateSmooth;
  25298. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  25299. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  25300. exports.WrapAroundEnding = WrapAroundEnding;
  25301. exports.TrianglesDrawMode = TrianglesDrawMode;
  25302. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  25303. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  25304. exports.LinearEncoding = LinearEncoding;
  25305. exports.sRGBEncoding = sRGBEncoding;
  25306. exports.GammaEncoding = GammaEncoding;
  25307. exports.RGBEEncoding = RGBEEncoding;
  25308. exports.LogLuvEncoding = LogLuvEncoding;
  25309. exports.RGBM7Encoding = RGBM7Encoding;
  25310. exports.RGBM16Encoding = RGBM16Encoding;
  25311. exports.RGBDEncoding = RGBDEncoding;
  25312. exports.BasicDepthPacking = BasicDepthPacking;
  25313. exports.RGBADepthPacking = RGBADepthPacking;
  25314. exports.CubeGeometry = BoxGeometry;
  25315. exports.Face4 = Face4;
  25316. exports.LineStrip = LineStrip;
  25317. exports.LinePieces = LinePieces;
  25318. exports.MeshFaceMaterial = MultiMaterial;
  25319. exports.PointCloud = PointCloud;
  25320. exports.Particle = Sprite;
  25321. exports.ParticleSystem = ParticleSystem;
  25322. exports.PointCloudMaterial = PointCloudMaterial;
  25323. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  25324. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  25325. exports.Vertex = Vertex;
  25326. exports.GeometryUtils = GeometryUtils;
  25327. exports.ImageUtils = ImageUtils;
  25328. exports.Projector = Projector;
  25329. exports.CanvasRenderer = CanvasRenderer;
  25330. Object.defineProperty(exports, '__esModule', { value: true });
  25331. })));