WebGLRenderer.js 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. */
  7. THREE.WebGLRenderer = function ( parameters ) {
  8. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9. parameters = parameters || {};
  10. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11. _context = parameters.context !== undefined ? parameters.context : null,
  12. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  13. _buffers = {},
  14. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  18. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  19. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  21. _clearColor = new THREE.Color( 0x000000 ),
  22. _clearAlpha = 0;
  23. var opaqueObjects = [];
  24. var transparentObjects = [];
  25. var _sortObjects = true;
  26. // public properties
  27. this.domElement = _canvas;
  28. this.context = null;
  29. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  30. ? parameters.devicePixelRatio
  31. : self.devicePixelRatio !== undefined
  32. ? self.devicePixelRatio
  33. : 1;
  34. // clearing
  35. this.autoClear = true;
  36. this.autoClearColor = true;
  37. this.autoClearDepth = true;
  38. this.autoClearStencil = true;
  39. // scene graph
  40. this.sortObjects = true;
  41. this.autoUpdateObjects = true;
  42. // physically based shading
  43. this.gammaInput = false;
  44. this.gammaOutput = false;
  45. // shadow map
  46. this.shadowMapEnabled = false;
  47. this.shadowMapAutoUpdate = true;
  48. this.shadowMapType = THREE.PCFShadowMap;
  49. this.shadowMapCullFace = THREE.CullFaceFront;
  50. this.shadowMapDebug = false;
  51. this.shadowMapCascade = false;
  52. // morphs
  53. this.maxMorphTargets = 8;
  54. this.maxMorphNormals = 4;
  55. // flags
  56. this.autoScaleCubemaps = true;
  57. // custom render plugins
  58. this.renderPluginsPre = [];
  59. this.renderPluginsPost = [];
  60. // info
  61. this.info = {
  62. memory: {
  63. programs: 0,
  64. geometries: 0,
  65. textures: 0
  66. },
  67. render: {
  68. calls: 0,
  69. vertices: 0,
  70. faces: 0,
  71. points: 0
  72. }
  73. };
  74. // internal properties
  75. var _this = this,
  76. _programs = [],
  77. // internal state cache
  78. _currentProgram = null,
  79. _currentFramebuffer = null,
  80. _currentMaterialId = - 1,
  81. _currentGeometryGroupHash = null,
  82. _currentCamera = null,
  83. _usedTextureUnits = 0,
  84. // GL state cache
  85. _oldDoubleSided = - 1,
  86. _oldFlipSided = - 1,
  87. _oldBlending = - 1,
  88. _oldBlendEquation = - 1,
  89. _oldBlendSrc = - 1,
  90. _oldBlendDst = - 1,
  91. _oldDepthTest = - 1,
  92. _oldDepthWrite = - 1,
  93. _oldPolygonOffset = null,
  94. _oldPolygonOffsetFactor = null,
  95. _oldPolygonOffsetUnits = null,
  96. _oldLineWidth = null,
  97. _viewportX = 0,
  98. _viewportY = 0,
  99. _viewportWidth = _canvas.width,
  100. _viewportHeight = _canvas.height,
  101. _currentWidth = 0,
  102. _currentHeight = 0,
  103. _newAttributes = new Uint8Array( 16 ),
  104. _enabledAttributes = new Uint8Array( 16 ),
  105. // frustum
  106. _frustum = new THREE.Frustum(),
  107. // camera matrices cache
  108. _projScreenMatrix = new THREE.Matrix4(),
  109. _projScreenMatrixPS = new THREE.Matrix4(),
  110. _vector3 = new THREE.Vector3(),
  111. // light arrays cache
  112. _direction = new THREE.Vector3(),
  113. _lightsNeedUpdate = true,
  114. _lights = {
  115. ambient: [ 0, 0, 0 ],
  116. directional: { length: 0, colors: new Array(), positions: new Array() },
  117. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  118. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  119. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  120. };
  121. // initialize
  122. var _gl;
  123. var _glExtensionTextureFloat;
  124. var _glExtensionTextureFloatLinear;
  125. var _glExtensionStandardDerivatives;
  126. var _glExtensionTextureFilterAnisotropic;
  127. var _glExtensionCompressedTextureS3TC;
  128. var _glExtensionElementIndexUint;
  129. var _glExtensionFragDepth;
  130. initGL();
  131. setDefaultGLState();
  132. this.context = _gl;
  133. // GPU capabilities
  134. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  135. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  136. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  137. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  138. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  139. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  140. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  141. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  142. //
  143. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  144. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  145. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  146. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  147. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  148. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  149. /*
  150. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  151. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  152. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  153. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  154. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  155. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  156. */
  157. // clamp precision to maximum available
  158. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  159. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  160. if ( _precision === 'highp' && ! highpAvailable ) {
  161. if ( mediumpAvailable ) {
  162. _precision = 'mediump';
  163. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  164. } else {
  165. _precision = 'lowp';
  166. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  167. }
  168. }
  169. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  170. _precision = 'lowp';
  171. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  172. }
  173. // API
  174. this.getContext = function () {
  175. return _gl;
  176. };
  177. this.supportsVertexTextures = function () {
  178. return _supportsVertexTextures;
  179. };
  180. this.supportsFloatTextures = function () {
  181. return _glExtensionTextureFloat;
  182. };
  183. this.supportsStandardDerivatives = function () {
  184. return _glExtensionStandardDerivatives;
  185. };
  186. this.supportsCompressedTextureS3TC = function () {
  187. return _glExtensionCompressedTextureS3TC;
  188. };
  189. this.getMaxAnisotropy = function () {
  190. return _maxAnisotropy;
  191. };
  192. this.getPrecision = function () {
  193. return _precision;
  194. };
  195. this.setSize = function ( width, height, updateStyle ) {
  196. _canvas.width = width * this.devicePixelRatio;
  197. _canvas.height = height * this.devicePixelRatio;
  198. if ( updateStyle !== false ) {
  199. _canvas.style.width = width + 'px';
  200. _canvas.style.height = height + 'px';
  201. }
  202. this.setViewport( 0, 0, width, height );
  203. };
  204. this.setViewport = function ( x, y, width, height ) {
  205. _viewportX = x * this.devicePixelRatio;
  206. _viewportY = y * this.devicePixelRatio;
  207. _viewportWidth = width * this.devicePixelRatio;
  208. _viewportHeight = height * this.devicePixelRatio;
  209. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  210. };
  211. this.setScissor = function ( x, y, width, height ) {
  212. _gl.scissor(
  213. x * this.devicePixelRatio,
  214. y * this.devicePixelRatio,
  215. width * this.devicePixelRatio,
  216. height * this.devicePixelRatio
  217. );
  218. };
  219. this.enableScissorTest = function ( enable ) {
  220. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  221. };
  222. // Clearing
  223. this.setClearColor = function ( color, alpha ) {
  224. _clearColor.set( color );
  225. _clearAlpha = alpha !== undefined ? alpha : 1;
  226. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  227. };
  228. this.setClearColorHex = function ( hex, alpha ) {
  229. console.warn( 'THREE.WebGLRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  230. this.setClearColor( hex, alpha );
  231. };
  232. this.getClearColor = function () {
  233. return _clearColor;
  234. };
  235. this.getClearAlpha = function () {
  236. return _clearAlpha;
  237. };
  238. this.clear = function ( color, depth, stencil ) {
  239. var bits = 0;
  240. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  241. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  242. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  243. _gl.clear( bits );
  244. };
  245. this.clearColor = function () {
  246. _gl.clear( _gl.COLOR_BUFFER_BIT );
  247. };
  248. this.clearDepth = function () {
  249. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  250. };
  251. this.clearStencil = function () {
  252. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  253. };
  254. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  255. this.setRenderTarget( renderTarget );
  256. this.clear( color, depth, stencil );
  257. };
  258. // Plugins
  259. this.addPostPlugin = function ( plugin ) {
  260. plugin.init( this );
  261. this.renderPluginsPost.push( plugin );
  262. };
  263. this.addPrePlugin = function ( plugin ) {
  264. plugin.init( this );
  265. this.renderPluginsPre.push( plugin );
  266. };
  267. // Rendering
  268. this.updateShadowMap = function ( scene, camera ) {
  269. _currentProgram = null;
  270. _oldBlending = - 1;
  271. _oldDepthTest = - 1;
  272. _oldDepthWrite = - 1;
  273. _currentGeometryGroupHash = - 1;
  274. _currentMaterialId = - 1;
  275. _lightsNeedUpdate = true;
  276. _oldDoubleSided = - 1;
  277. _oldFlipSided = - 1;
  278. this.shadowMapPlugin.update( scene, camera );
  279. };
  280. // Internal functions
  281. // Buffer allocation
  282. function createParticleBuffers ( geometry ) {
  283. geometry.__webglVertexBuffer = _gl.createBuffer();
  284. geometry.__webglColorBuffer = _gl.createBuffer();
  285. _this.info.memory.geometries ++;
  286. };
  287. function createLineBuffers ( geometry ) {
  288. geometry.__webglVertexBuffer = _gl.createBuffer();
  289. geometry.__webglColorBuffer = _gl.createBuffer();
  290. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  291. _this.info.memory.geometries ++;
  292. };
  293. function createMeshBuffers ( geometryGroup ) {
  294. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  295. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  296. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  297. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  298. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  299. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  300. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  301. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  302. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  303. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  304. var m, ml;
  305. if ( geometryGroup.numMorphTargets ) {
  306. geometryGroup.__webglMorphTargetsBuffers = [];
  307. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  308. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  309. }
  310. }
  311. if ( geometryGroup.numMorphNormals ) {
  312. geometryGroup.__webglMorphNormalsBuffers = [];
  313. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  314. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  315. }
  316. }
  317. _this.info.memory.geometries ++;
  318. };
  319. // Events
  320. var onGeometryDispose = function ( event ) {
  321. var geometry = event.target;
  322. geometry.removeEventListener( 'dispose', onGeometryDispose );
  323. deallocateGeometry( geometry );
  324. };
  325. var onTextureDispose = function ( event ) {
  326. var texture = event.target;
  327. texture.removeEventListener( 'dispose', onTextureDispose );
  328. deallocateTexture( texture );
  329. _this.info.memory.textures --;
  330. };
  331. var onRenderTargetDispose = function ( event ) {
  332. var renderTarget = event.target;
  333. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  334. deallocateRenderTarget( renderTarget );
  335. _this.info.memory.textures --;
  336. };
  337. var onMaterialDispose = function ( event ) {
  338. var material = event.target;
  339. material.removeEventListener( 'dispose', onMaterialDispose );
  340. deallocateMaterial( material );
  341. };
  342. // Buffer deallocation
  343. var deleteBuffers = function ( geometry ) {
  344. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  345. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  346. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  347. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  348. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  349. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  350. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  351. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  352. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  353. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  354. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  355. // custom attributes
  356. if ( geometry.__webglCustomAttributesList !== undefined ) {
  357. for ( var id in geometry.__webglCustomAttributesList ) {
  358. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  359. }
  360. }
  361. _this.info.memory.geometries --;
  362. };
  363. var deallocateGeometry = function ( geometry ) {
  364. geometry.__webglInit = undefined;
  365. if ( geometry instanceof THREE.BufferGeometry ) {
  366. var attributes = geometry.attributes;
  367. for ( var key in attributes ) {
  368. if ( attributes[ key ].buffer !== undefined ) {
  369. _gl.deleteBuffer( attributes[ key ].buffer );
  370. }
  371. }
  372. _this.info.memory.geometries --;
  373. } else {
  374. if ( geometry.geometryGroups !== undefined ) {
  375. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  376. var geometryGroup = geometry.geometryGroupsList[ i ];
  377. if ( geometryGroup.numMorphTargets !== undefined ) {
  378. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  379. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  380. }
  381. }
  382. if ( geometryGroup.numMorphNormals !== undefined ) {
  383. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  384. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  385. }
  386. }
  387. deleteBuffers( geometryGroup );
  388. }
  389. } else {
  390. deleteBuffers( geometry );
  391. }
  392. }
  393. };
  394. var deallocateTexture = function ( texture ) {
  395. if ( texture.image && texture.image.__webglTextureCube ) {
  396. // cube texture
  397. _gl.deleteTexture( texture.image.__webglTextureCube );
  398. } else {
  399. // 2D texture
  400. if ( ! texture.__webglInit ) return;
  401. texture.__webglInit = false;
  402. _gl.deleteTexture( texture.__webglTexture );
  403. }
  404. };
  405. var deallocateRenderTarget = function ( renderTarget ) {
  406. if ( ! renderTarget || ! renderTarget.__webglTexture ) return;
  407. _gl.deleteTexture( renderTarget.__webglTexture );
  408. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  409. for ( var i = 0; i < 6; i ++ ) {
  410. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  411. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  412. }
  413. } else {
  414. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  415. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  416. }
  417. };
  418. var deallocateMaterial = function ( material ) {
  419. var program = material.program.program;
  420. if ( program === undefined ) return;
  421. material.program = undefined;
  422. // only deallocate GL program if this was the last use of shared program
  423. // assumed there is only single copy of any program in the _programs list
  424. // (that's how it's constructed)
  425. var i, il, programInfo;
  426. var deleteProgram = false;
  427. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  428. programInfo = _programs[ i ];
  429. if ( programInfo.program === program ) {
  430. programInfo.usedTimes --;
  431. if ( programInfo.usedTimes === 0 ) {
  432. deleteProgram = true;
  433. }
  434. break;
  435. }
  436. }
  437. if ( deleteProgram === true ) {
  438. // avoid using array.splice, this is costlier than creating new array from scratch
  439. var newPrograms = [];
  440. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  441. programInfo = _programs[ i ];
  442. if ( programInfo.program !== program ) {
  443. newPrograms.push( programInfo );
  444. }
  445. }
  446. _programs = newPrograms;
  447. _gl.deleteProgram( program );
  448. _this.info.memory.programs --;
  449. }
  450. };
  451. // Buffer initialization
  452. function initCustomAttributes ( geometry, object ) {
  453. var nvertices = geometry.vertices.length;
  454. var material = object.material;
  455. if ( material.attributes ) {
  456. if ( geometry.__webglCustomAttributesList === undefined ) {
  457. geometry.__webglCustomAttributesList = [];
  458. }
  459. for ( var a in material.attributes ) {
  460. var attribute = material.attributes[ a ];
  461. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  462. attribute.__webglInitialized = true;
  463. var size = 1; // "f" and "i"
  464. if ( attribute.type === 'v2' ) size = 2;
  465. else if ( attribute.type === 'v3' ) size = 3;
  466. else if ( attribute.type === 'v4' ) size = 4;
  467. else if ( attribute.type === 'c' ) size = 3;
  468. attribute.size = size;
  469. attribute.array = new Float32Array( nvertices * size );
  470. attribute.buffer = _gl.createBuffer();
  471. attribute.buffer.belongsToAttribute = a;
  472. attribute.needsUpdate = true;
  473. }
  474. geometry.__webglCustomAttributesList.push( attribute );
  475. }
  476. }
  477. };
  478. function initParticleBuffers ( geometry, object ) {
  479. var nvertices = geometry.vertices.length;
  480. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  481. geometry.__colorArray = new Float32Array( nvertices * 3 );
  482. geometry.__sortArray = [];
  483. geometry.__webglParticleCount = nvertices;
  484. initCustomAttributes ( geometry, object );
  485. };
  486. function initLineBuffers ( geometry, object ) {
  487. var nvertices = geometry.vertices.length;
  488. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  489. geometry.__colorArray = new Float32Array( nvertices * 3 );
  490. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  491. geometry.__webglLineCount = nvertices;
  492. initCustomAttributes ( geometry, object );
  493. };
  494. function initMeshBuffers ( geometryGroup, object ) {
  495. var geometry = object.geometry,
  496. faces3 = geometryGroup.faces3,
  497. nvertices = faces3.length * 3,
  498. ntris = faces3.length * 1,
  499. nlines = faces3.length * 3,
  500. material = getBufferMaterial( object, geometryGroup ),
  501. uvType = bufferGuessUVType( material ),
  502. normalType = bufferGuessNormalType( material ),
  503. vertexColorType = bufferGuessVertexColorType( material );
  504. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  505. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  506. if ( normalType ) {
  507. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  508. }
  509. if ( geometry.hasTangents ) {
  510. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  511. }
  512. if ( vertexColorType ) {
  513. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  514. }
  515. if ( uvType ) {
  516. if ( geometry.faceVertexUvs.length > 0 ) {
  517. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  518. }
  519. if ( geometry.faceVertexUvs.length > 1 ) {
  520. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  521. }
  522. }
  523. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  524. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  525. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  526. }
  527. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  528. geometryGroup.__typeArray = UintArray;
  529. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  530. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  531. var m, ml;
  532. if ( geometryGroup.numMorphTargets ) {
  533. geometryGroup.__morphTargetsArrays = [];
  534. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  535. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  536. }
  537. }
  538. if ( geometryGroup.numMorphNormals ) {
  539. geometryGroup.__morphNormalsArrays = [];
  540. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  541. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  542. }
  543. }
  544. geometryGroup.__webglFaceCount = ntris * 3;
  545. geometryGroup.__webglLineCount = nlines * 2;
  546. // custom attributes
  547. if ( material.attributes ) {
  548. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  549. geometryGroup.__webglCustomAttributesList = [];
  550. }
  551. for ( var a in material.attributes ) {
  552. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  553. // attribute buffers which are correctly indexed in the setMeshBuffers function
  554. var originalAttribute = material.attributes[ a ];
  555. var attribute = {};
  556. for ( var property in originalAttribute ) {
  557. attribute[ property ] = originalAttribute[ property ];
  558. }
  559. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  560. attribute.__webglInitialized = true;
  561. var size = 1; // "f" and "i"
  562. if ( attribute.type === 'v2' ) size = 2;
  563. else if ( attribute.type === 'v3' ) size = 3;
  564. else if ( attribute.type === 'v4' ) size = 4;
  565. else if ( attribute.type === 'c' ) size = 3;
  566. attribute.size = size;
  567. attribute.array = new Float32Array( nvertices * size );
  568. attribute.buffer = _gl.createBuffer();
  569. attribute.buffer.belongsToAttribute = a;
  570. originalAttribute.needsUpdate = true;
  571. attribute.__original = originalAttribute;
  572. }
  573. geometryGroup.__webglCustomAttributesList.push( attribute );
  574. }
  575. }
  576. geometryGroup.__inittedArrays = true;
  577. };
  578. function getBufferMaterial( object, geometryGroup ) {
  579. return object.material instanceof THREE.MeshFaceMaterial
  580. ? object.material.materials[ geometryGroup.materialIndex ]
  581. : object.material;
  582. };
  583. function materialNeedsSmoothNormals ( material ) {
  584. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  585. };
  586. function bufferGuessNormalType ( material ) {
  587. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  588. if ( ( material instanceof THREE.MeshBasicMaterial && ! material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  589. return false;
  590. }
  591. if ( materialNeedsSmoothNormals( material ) ) {
  592. return THREE.SmoothShading;
  593. } else {
  594. return THREE.FlatShading;
  595. }
  596. };
  597. function bufferGuessVertexColorType( material ) {
  598. if ( material.vertexColors ) {
  599. return material.vertexColors;
  600. }
  601. return false;
  602. };
  603. function bufferGuessUVType( material ) {
  604. // material must use some texture to require uvs
  605. if ( material.map ||
  606. material.lightMap ||
  607. material.bumpMap ||
  608. material.normalMap ||
  609. material.specularMap ||
  610. material instanceof THREE.ShaderMaterial ) {
  611. return true;
  612. }
  613. return false;
  614. };
  615. //
  616. function initDirectBuffers( geometry ) {
  617. for ( var name in geometry.attributes ) {
  618. var bufferType = ( name === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  619. var attribute = geometry.attributes[ name ];
  620. attribute.buffer = _gl.createBuffer();
  621. _gl.bindBuffer( bufferType, attribute.buffer );
  622. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  623. }
  624. }
  625. // Buffer setting
  626. function setParticleBuffers ( geometry, hint, object ) {
  627. var v, c, vertex, offset, index, color,
  628. vertices = geometry.vertices,
  629. vl = vertices.length,
  630. colors = geometry.colors,
  631. cl = colors.length,
  632. vertexArray = geometry.__vertexArray,
  633. colorArray = geometry.__colorArray,
  634. sortArray = geometry.__sortArray,
  635. dirtyVertices = geometry.verticesNeedUpdate,
  636. dirtyElements = geometry.elementsNeedUpdate,
  637. dirtyColors = geometry.colorsNeedUpdate,
  638. customAttributes = geometry.__webglCustomAttributesList,
  639. i, il,
  640. a, ca, cal, value,
  641. customAttribute;
  642. if ( object.sortParticles ) {
  643. _projScreenMatrixPS.copy( _projScreenMatrix );
  644. _projScreenMatrixPS.multiply( object.matrixWorld );
  645. for ( v = 0; v < vl; v ++ ) {
  646. vertex = vertices[ v ];
  647. _vector3.copy( vertex );
  648. _vector3.applyProjection( _projScreenMatrixPS );
  649. sortArray[ v ] = [ _vector3.z, v ];
  650. }
  651. sortArray.sort( numericalSort );
  652. for ( v = 0; v < vl; v ++ ) {
  653. vertex = vertices[ sortArray[ v ][ 1 ] ];
  654. offset = v * 3;
  655. vertexArray[ offset ] = vertex.x;
  656. vertexArray[ offset + 1 ] = vertex.y;
  657. vertexArray[ offset + 2 ] = vertex.z;
  658. }
  659. for ( c = 0; c < cl; c ++ ) {
  660. offset = c * 3;
  661. color = colors[ sortArray[ c ][ 1 ] ];
  662. colorArray[ offset ] = color.r;
  663. colorArray[ offset + 1 ] = color.g;
  664. colorArray[ offset + 2 ] = color.b;
  665. }
  666. if ( customAttributes ) {
  667. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  668. customAttribute = customAttributes[ i ];
  669. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) continue;
  670. offset = 0;
  671. cal = customAttribute.value.length;
  672. if ( customAttribute.size === 1 ) {
  673. for ( ca = 0; ca < cal; ca ++ ) {
  674. index = sortArray[ ca ][ 1 ];
  675. customAttribute.array[ ca ] = customAttribute.value[ index ];
  676. }
  677. } else if ( customAttribute.size === 2 ) {
  678. for ( ca = 0; ca < cal; ca ++ ) {
  679. index = sortArray[ ca ][ 1 ];
  680. value = customAttribute.value[ index ];
  681. customAttribute.array[ offset ] = value.x;
  682. customAttribute.array[ offset + 1 ] = value.y;
  683. offset += 2;
  684. }
  685. } else if ( customAttribute.size === 3 ) {
  686. if ( customAttribute.type === 'c' ) {
  687. for ( ca = 0; ca < cal; ca ++ ) {
  688. index = sortArray[ ca ][ 1 ];
  689. value = customAttribute.value[ index ];
  690. customAttribute.array[ offset ] = value.r;
  691. customAttribute.array[ offset + 1 ] = value.g;
  692. customAttribute.array[ offset + 2 ] = value.b;
  693. offset += 3;
  694. }
  695. } else {
  696. for ( ca = 0; ca < cal; ca ++ ) {
  697. index = sortArray[ ca ][ 1 ];
  698. value = customAttribute.value[ index ];
  699. customAttribute.array[ offset ] = value.x;
  700. customAttribute.array[ offset + 1 ] = value.y;
  701. customAttribute.array[ offset + 2 ] = value.z;
  702. offset += 3;
  703. }
  704. }
  705. } else if ( customAttribute.size === 4 ) {
  706. for ( ca = 0; ca < cal; ca ++ ) {
  707. index = sortArray[ ca ][ 1 ];
  708. value = customAttribute.value[ index ];
  709. customAttribute.array[ offset ] = value.x;
  710. customAttribute.array[ offset + 1 ] = value.y;
  711. customAttribute.array[ offset + 2 ] = value.z;
  712. customAttribute.array[ offset + 3 ] = value.w;
  713. offset += 4;
  714. }
  715. }
  716. }
  717. }
  718. } else {
  719. if ( dirtyVertices ) {
  720. for ( v = 0; v < vl; v ++ ) {
  721. vertex = vertices[ v ];
  722. offset = v * 3;
  723. vertexArray[ offset ] = vertex.x;
  724. vertexArray[ offset + 1 ] = vertex.y;
  725. vertexArray[ offset + 2 ] = vertex.z;
  726. }
  727. }
  728. if ( dirtyColors ) {
  729. for ( c = 0; c < cl; c ++ ) {
  730. color = colors[ c ];
  731. offset = c * 3;
  732. colorArray[ offset ] = color.r;
  733. colorArray[ offset + 1 ] = color.g;
  734. colorArray[ offset + 2 ] = color.b;
  735. }
  736. }
  737. if ( customAttributes ) {
  738. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  739. customAttribute = customAttributes[ i ];
  740. if ( customAttribute.needsUpdate &&
  741. ( customAttribute.boundTo === undefined ||
  742. customAttribute.boundTo === 'vertices' ) ) {
  743. cal = customAttribute.value.length;
  744. offset = 0;
  745. if ( customAttribute.size === 1 ) {
  746. for ( ca = 0; ca < cal; ca ++ ) {
  747. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  748. }
  749. } else if ( customAttribute.size === 2 ) {
  750. for ( ca = 0; ca < cal; ca ++ ) {
  751. value = customAttribute.value[ ca ];
  752. customAttribute.array[ offset ] = value.x;
  753. customAttribute.array[ offset + 1 ] = value.y;
  754. offset += 2;
  755. }
  756. } else if ( customAttribute.size === 3 ) {
  757. if ( customAttribute.type === 'c' ) {
  758. for ( ca = 0; ca < cal; ca ++ ) {
  759. value = customAttribute.value[ ca ];
  760. customAttribute.array[ offset ] = value.r;
  761. customAttribute.array[ offset + 1 ] = value.g;
  762. customAttribute.array[ offset + 2 ] = value.b;
  763. offset += 3;
  764. }
  765. } else {
  766. for ( ca = 0; ca < cal; ca ++ ) {
  767. value = customAttribute.value[ ca ];
  768. customAttribute.array[ offset ] = value.x;
  769. customAttribute.array[ offset + 1 ] = value.y;
  770. customAttribute.array[ offset + 2 ] = value.z;
  771. offset += 3;
  772. }
  773. }
  774. } else if ( customAttribute.size === 4 ) {
  775. for ( ca = 0; ca < cal; ca ++ ) {
  776. value = customAttribute.value[ ca ];
  777. customAttribute.array[ offset ] = value.x;
  778. customAttribute.array[ offset + 1 ] = value.y;
  779. customAttribute.array[ offset + 2 ] = value.z;
  780. customAttribute.array[ offset + 3 ] = value.w;
  781. offset += 4;
  782. }
  783. }
  784. }
  785. }
  786. }
  787. }
  788. if ( dirtyVertices || object.sortParticles ) {
  789. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  790. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  791. }
  792. if ( dirtyColors || object.sortParticles ) {
  793. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  794. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  795. }
  796. if ( customAttributes ) {
  797. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  798. customAttribute = customAttributes[ i ];
  799. if ( customAttribute.needsUpdate || object.sortParticles ) {
  800. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  801. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  802. }
  803. }
  804. }
  805. }
  806. function setLineBuffers ( geometry, hint ) {
  807. var v, c, d, vertex, offset, color,
  808. vertices = geometry.vertices,
  809. colors = geometry.colors,
  810. lineDistances = geometry.lineDistances,
  811. vl = vertices.length,
  812. cl = colors.length,
  813. dl = lineDistances.length,
  814. vertexArray = geometry.__vertexArray,
  815. colorArray = geometry.__colorArray,
  816. lineDistanceArray = geometry.__lineDistanceArray,
  817. dirtyVertices = geometry.verticesNeedUpdate,
  818. dirtyColors = geometry.colorsNeedUpdate,
  819. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  820. customAttributes = geometry.__webglCustomAttributesList,
  821. i, il,
  822. a, ca, cal, value,
  823. customAttribute;
  824. if ( dirtyVertices ) {
  825. for ( v = 0; v < vl; v ++ ) {
  826. vertex = vertices[ v ];
  827. offset = v * 3;
  828. vertexArray[ offset ] = vertex.x;
  829. vertexArray[ offset + 1 ] = vertex.y;
  830. vertexArray[ offset + 2 ] = vertex.z;
  831. }
  832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  833. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  834. }
  835. if ( dirtyColors ) {
  836. for ( c = 0; c < cl; c ++ ) {
  837. color = colors[ c ];
  838. offset = c * 3;
  839. colorArray[ offset ] = color.r;
  840. colorArray[ offset + 1 ] = color.g;
  841. colorArray[ offset + 2 ] = color.b;
  842. }
  843. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  844. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  845. }
  846. if ( dirtyLineDistances ) {
  847. for ( d = 0; d < dl; d ++ ) {
  848. lineDistanceArray[ d ] = lineDistances[ d ];
  849. }
  850. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  851. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  852. }
  853. if ( customAttributes ) {
  854. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  855. customAttribute = customAttributes[ i ];
  856. if ( customAttribute.needsUpdate &&
  857. ( customAttribute.boundTo === undefined ||
  858. customAttribute.boundTo === 'vertices' ) ) {
  859. offset = 0;
  860. cal = customAttribute.value.length;
  861. if ( customAttribute.size === 1 ) {
  862. for ( ca = 0; ca < cal; ca ++ ) {
  863. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  864. }
  865. } else if ( customAttribute.size === 2 ) {
  866. for ( ca = 0; ca < cal; ca ++ ) {
  867. value = customAttribute.value[ ca ];
  868. customAttribute.array[ offset ] = value.x;
  869. customAttribute.array[ offset + 1 ] = value.y;
  870. offset += 2;
  871. }
  872. } else if ( customAttribute.size === 3 ) {
  873. if ( customAttribute.type === 'c' ) {
  874. for ( ca = 0; ca < cal; ca ++ ) {
  875. value = customAttribute.value[ ca ];
  876. customAttribute.array[ offset ] = value.r;
  877. customAttribute.array[ offset + 1 ] = value.g;
  878. customAttribute.array[ offset + 2 ] = value.b;
  879. offset += 3;
  880. }
  881. } else {
  882. for ( ca = 0; ca < cal; ca ++ ) {
  883. value = customAttribute.value[ ca ];
  884. customAttribute.array[ offset ] = value.x;
  885. customAttribute.array[ offset + 1 ] = value.y;
  886. customAttribute.array[ offset + 2 ] = value.z;
  887. offset += 3;
  888. }
  889. }
  890. } else if ( customAttribute.size === 4 ) {
  891. for ( ca = 0; ca < cal; ca ++ ) {
  892. value = customAttribute.value[ ca ];
  893. customAttribute.array[ offset ] = value.x;
  894. customAttribute.array[ offset + 1 ] = value.y;
  895. customAttribute.array[ offset + 2 ] = value.z;
  896. customAttribute.array[ offset + 3 ] = value.w;
  897. offset += 4;
  898. }
  899. }
  900. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  901. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  902. }
  903. }
  904. }
  905. }
  906. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  907. if ( ! geometryGroup.__inittedArrays ) {
  908. return;
  909. }
  910. var normalType = bufferGuessNormalType( material ),
  911. vertexColorType = bufferGuessVertexColorType( material ),
  912. uvType = bufferGuessUVType( material ),
  913. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  914. var f, fl, fi, face,
  915. vertexNormals, faceNormal, normal,
  916. vertexColors, faceColor,
  917. vertexTangents,
  918. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  919. c1, c2, c3,
  920. sw1, sw2, sw3, sw4,
  921. si1, si2, si3, si4,
  922. sa1, sa2, sa3, sa4,
  923. sb1, sb2, sb3, sb4,
  924. m, ml, i, il,
  925. vn, uvi, uv2i,
  926. vk, vkl, vka,
  927. nka, chf, faceVertexNormals,
  928. a,
  929. vertexIndex = 0,
  930. offset = 0,
  931. offset_uv = 0,
  932. offset_uv2 = 0,
  933. offset_face = 0,
  934. offset_normal = 0,
  935. offset_tangent = 0,
  936. offset_line = 0,
  937. offset_color = 0,
  938. offset_skin = 0,
  939. offset_morphTarget = 0,
  940. offset_custom = 0,
  941. offset_customSrc = 0,
  942. value,
  943. vertexArray = geometryGroup.__vertexArray,
  944. uvArray = geometryGroup.__uvArray,
  945. uv2Array = geometryGroup.__uv2Array,
  946. normalArray = geometryGroup.__normalArray,
  947. tangentArray = geometryGroup.__tangentArray,
  948. colorArray = geometryGroup.__colorArray,
  949. skinIndexArray = geometryGroup.__skinIndexArray,
  950. skinWeightArray = geometryGroup.__skinWeightArray,
  951. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  952. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  953. customAttributes = geometryGroup.__webglCustomAttributesList,
  954. customAttribute,
  955. faceArray = geometryGroup.__faceArray,
  956. lineArray = geometryGroup.__lineArray,
  957. geometry = object.geometry, // this is shared for all chunks
  958. dirtyVertices = geometry.verticesNeedUpdate,
  959. dirtyElements = geometry.elementsNeedUpdate,
  960. dirtyUvs = geometry.uvsNeedUpdate,
  961. dirtyNormals = geometry.normalsNeedUpdate,
  962. dirtyTangents = geometry.tangentsNeedUpdate,
  963. dirtyColors = geometry.colorsNeedUpdate,
  964. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  965. vertices = geometry.vertices,
  966. chunk_faces3 = geometryGroup.faces3,
  967. obj_faces = geometry.faces,
  968. obj_uvs = geometry.faceVertexUvs[ 0 ],
  969. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  970. obj_colors = geometry.colors,
  971. obj_skinIndices = geometry.skinIndices,
  972. obj_skinWeights = geometry.skinWeights,
  973. morphTargets = geometry.morphTargets,
  974. morphNormals = geometry.morphNormals;
  975. if ( dirtyVertices ) {
  976. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  977. face = obj_faces[ chunk_faces3[ f ] ];
  978. v1 = vertices[ face.a ];
  979. v2 = vertices[ face.b ];
  980. v3 = vertices[ face.c ];
  981. vertexArray[ offset ] = v1.x;
  982. vertexArray[ offset + 1 ] = v1.y;
  983. vertexArray[ offset + 2 ] = v1.z;
  984. vertexArray[ offset + 3 ] = v2.x;
  985. vertexArray[ offset + 4 ] = v2.y;
  986. vertexArray[ offset + 5 ] = v2.z;
  987. vertexArray[ offset + 6 ] = v3.x;
  988. vertexArray[ offset + 7 ] = v3.y;
  989. vertexArray[ offset + 8 ] = v3.z;
  990. offset += 9;
  991. }
  992. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  993. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  994. }
  995. if ( dirtyMorphTargets ) {
  996. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  997. offset_morphTarget = 0;
  998. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  999. chf = chunk_faces3[ f ];
  1000. face = obj_faces[ chf ];
  1001. // morph positions
  1002. v1 = morphTargets[ vk ].vertices[ face.a ];
  1003. v2 = morphTargets[ vk ].vertices[ face.b ];
  1004. v3 = morphTargets[ vk ].vertices[ face.c ];
  1005. vka = morphTargetsArrays[ vk ];
  1006. vka[ offset_morphTarget ] = v1.x;
  1007. vka[ offset_morphTarget + 1 ] = v1.y;
  1008. vka[ offset_morphTarget + 2 ] = v1.z;
  1009. vka[ offset_morphTarget + 3 ] = v2.x;
  1010. vka[ offset_morphTarget + 4 ] = v2.y;
  1011. vka[ offset_morphTarget + 5 ] = v2.z;
  1012. vka[ offset_morphTarget + 6 ] = v3.x;
  1013. vka[ offset_morphTarget + 7 ] = v3.y;
  1014. vka[ offset_morphTarget + 8 ] = v3.z;
  1015. // morph normals
  1016. if ( material.morphNormals ) {
  1017. if ( needsSmoothNormals ) {
  1018. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  1019. n1 = faceVertexNormals.a;
  1020. n2 = faceVertexNormals.b;
  1021. n3 = faceVertexNormals.c;
  1022. } else {
  1023. n1 = morphNormals[ vk ].faceNormals[ chf ];
  1024. n2 = n1;
  1025. n3 = n1;
  1026. }
  1027. nka = morphNormalsArrays[ vk ];
  1028. nka[ offset_morphTarget ] = n1.x;
  1029. nka[ offset_morphTarget + 1 ] = n1.y;
  1030. nka[ offset_morphTarget + 2 ] = n1.z;
  1031. nka[ offset_morphTarget + 3 ] = n2.x;
  1032. nka[ offset_morphTarget + 4 ] = n2.y;
  1033. nka[ offset_morphTarget + 5 ] = n2.z;
  1034. nka[ offset_morphTarget + 6 ] = n3.x;
  1035. nka[ offset_morphTarget + 7 ] = n3.y;
  1036. nka[ offset_morphTarget + 8 ] = n3.z;
  1037. }
  1038. //
  1039. offset_morphTarget += 9;
  1040. }
  1041. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  1042. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  1043. if ( material.morphNormals ) {
  1044. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  1045. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  1046. }
  1047. }
  1048. }
  1049. if ( obj_skinWeights.length ) {
  1050. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1051. face = obj_faces[ chunk_faces3[ f ] ];
  1052. // weights
  1053. sw1 = obj_skinWeights[ face.a ];
  1054. sw2 = obj_skinWeights[ face.b ];
  1055. sw3 = obj_skinWeights[ face.c ];
  1056. skinWeightArray[ offset_skin ] = sw1.x;
  1057. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  1058. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  1059. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  1060. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  1061. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  1062. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  1063. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  1064. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  1065. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  1066. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  1067. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  1068. // indices
  1069. si1 = obj_skinIndices[ face.a ];
  1070. si2 = obj_skinIndices[ face.b ];
  1071. si3 = obj_skinIndices[ face.c ];
  1072. skinIndexArray[ offset_skin ] = si1.x;
  1073. skinIndexArray[ offset_skin + 1 ] = si1.y;
  1074. skinIndexArray[ offset_skin + 2 ] = si1.z;
  1075. skinIndexArray[ offset_skin + 3 ] = si1.w;
  1076. skinIndexArray[ offset_skin + 4 ] = si2.x;
  1077. skinIndexArray[ offset_skin + 5 ] = si2.y;
  1078. skinIndexArray[ offset_skin + 6 ] = si2.z;
  1079. skinIndexArray[ offset_skin + 7 ] = si2.w;
  1080. skinIndexArray[ offset_skin + 8 ] = si3.x;
  1081. skinIndexArray[ offset_skin + 9 ] = si3.y;
  1082. skinIndexArray[ offset_skin + 10 ] = si3.z;
  1083. skinIndexArray[ offset_skin + 11 ] = si3.w;
  1084. offset_skin += 12;
  1085. }
  1086. if ( offset_skin > 0 ) {
  1087. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1088. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  1089. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1090. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  1091. }
  1092. }
  1093. if ( dirtyColors && vertexColorType ) {
  1094. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1095. face = obj_faces[ chunk_faces3[ f ] ];
  1096. vertexColors = face.vertexColors;
  1097. faceColor = face.color;
  1098. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  1099. c1 = vertexColors[ 0 ];
  1100. c2 = vertexColors[ 1 ];
  1101. c3 = vertexColors[ 2 ];
  1102. } else {
  1103. c1 = faceColor;
  1104. c2 = faceColor;
  1105. c3 = faceColor;
  1106. }
  1107. colorArray[ offset_color ] = c1.r;
  1108. colorArray[ offset_color + 1 ] = c1.g;
  1109. colorArray[ offset_color + 2 ] = c1.b;
  1110. colorArray[ offset_color + 3 ] = c2.r;
  1111. colorArray[ offset_color + 4 ] = c2.g;
  1112. colorArray[ offset_color + 5 ] = c2.b;
  1113. colorArray[ offset_color + 6 ] = c3.r;
  1114. colorArray[ offset_color + 7 ] = c3.g;
  1115. colorArray[ offset_color + 8 ] = c3.b;
  1116. offset_color += 9;
  1117. }
  1118. if ( offset_color > 0 ) {
  1119. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1120. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  1121. }
  1122. }
  1123. if ( dirtyTangents && geometry.hasTangents ) {
  1124. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1125. face = obj_faces[ chunk_faces3[ f ] ];
  1126. vertexTangents = face.vertexTangents;
  1127. t1 = vertexTangents[ 0 ];
  1128. t2 = vertexTangents[ 1 ];
  1129. t3 = vertexTangents[ 2 ];
  1130. tangentArray[ offset_tangent ] = t1.x;
  1131. tangentArray[ offset_tangent + 1 ] = t1.y;
  1132. tangentArray[ offset_tangent + 2 ] = t1.z;
  1133. tangentArray[ offset_tangent + 3 ] = t1.w;
  1134. tangentArray[ offset_tangent + 4 ] = t2.x;
  1135. tangentArray[ offset_tangent + 5 ] = t2.y;
  1136. tangentArray[ offset_tangent + 6 ] = t2.z;
  1137. tangentArray[ offset_tangent + 7 ] = t2.w;
  1138. tangentArray[ offset_tangent + 8 ] = t3.x;
  1139. tangentArray[ offset_tangent + 9 ] = t3.y;
  1140. tangentArray[ offset_tangent + 10 ] = t3.z;
  1141. tangentArray[ offset_tangent + 11 ] = t3.w;
  1142. offset_tangent += 12;
  1143. }
  1144. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1145. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  1146. }
  1147. if ( dirtyNormals && normalType ) {
  1148. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1149. face = obj_faces[ chunk_faces3[ f ] ];
  1150. vertexNormals = face.vertexNormals;
  1151. faceNormal = face.normal;
  1152. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  1153. for ( i = 0; i < 3; i ++ ) {
  1154. vn = vertexNormals[ i ];
  1155. normalArray[ offset_normal ] = vn.x;
  1156. normalArray[ offset_normal + 1 ] = vn.y;
  1157. normalArray[ offset_normal + 2 ] = vn.z;
  1158. offset_normal += 3;
  1159. }
  1160. } else {
  1161. for ( i = 0; i < 3; i ++ ) {
  1162. normalArray[ offset_normal ] = faceNormal.x;
  1163. normalArray[ offset_normal + 1 ] = faceNormal.y;
  1164. normalArray[ offset_normal + 2 ] = faceNormal.z;
  1165. offset_normal += 3;
  1166. }
  1167. }
  1168. }
  1169. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1170. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  1171. }
  1172. if ( dirtyUvs && obj_uvs && uvType ) {
  1173. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1174. fi = chunk_faces3[ f ];
  1175. uv = obj_uvs[ fi ];
  1176. if ( uv === undefined ) continue;
  1177. for ( i = 0; i < 3; i ++ ) {
  1178. uvi = uv[ i ];
  1179. uvArray[ offset_uv ] = uvi.x;
  1180. uvArray[ offset_uv + 1 ] = uvi.y;
  1181. offset_uv += 2;
  1182. }
  1183. }
  1184. if ( offset_uv > 0 ) {
  1185. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1186. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  1187. }
  1188. }
  1189. if ( dirtyUvs && obj_uvs2 && uvType ) {
  1190. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1191. fi = chunk_faces3[ f ];
  1192. uv2 = obj_uvs2[ fi ];
  1193. if ( uv2 === undefined ) continue;
  1194. for ( i = 0; i < 3; i ++ ) {
  1195. uv2i = uv2[ i ];
  1196. uv2Array[ offset_uv2 ] = uv2i.x;
  1197. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  1198. offset_uv2 += 2;
  1199. }
  1200. }
  1201. if ( offset_uv2 > 0 ) {
  1202. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1203. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  1204. }
  1205. }
  1206. if ( dirtyElements ) {
  1207. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1208. faceArray[ offset_face ] = vertexIndex;
  1209. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  1210. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  1211. offset_face += 3;
  1212. lineArray[ offset_line ] = vertexIndex;
  1213. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  1214. lineArray[ offset_line + 2 ] = vertexIndex;
  1215. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  1216. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  1217. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  1218. offset_line += 6;
  1219. vertexIndex += 3;
  1220. }
  1221. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1222. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  1223. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1224. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  1225. }
  1226. if ( customAttributes ) {
  1227. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  1228. customAttribute = customAttributes[ i ];
  1229. if ( ! customAttribute.__original.needsUpdate ) continue;
  1230. offset_custom = 0;
  1231. offset_customSrc = 0;
  1232. if ( customAttribute.size === 1 ) {
  1233. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1234. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1235. face = obj_faces[ chunk_faces3[ f ] ];
  1236. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  1237. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  1238. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  1239. offset_custom += 3;
  1240. }
  1241. } else if ( customAttribute.boundTo === 'faces' ) {
  1242. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1243. value = customAttribute.value[ chunk_faces3[ f ] ];
  1244. customAttribute.array[ offset_custom ] = value;
  1245. customAttribute.array[ offset_custom + 1 ] = value;
  1246. customAttribute.array[ offset_custom + 2 ] = value;
  1247. offset_custom += 3;
  1248. }
  1249. }
  1250. } else if ( customAttribute.size === 2 ) {
  1251. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1252. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1253. face = obj_faces[ chunk_faces3[ f ] ];
  1254. v1 = customAttribute.value[ face.a ];
  1255. v2 = customAttribute.value[ face.b ];
  1256. v3 = customAttribute.value[ face.c ];
  1257. customAttribute.array[ offset_custom ] = v1.x;
  1258. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1259. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1260. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1261. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1262. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1263. offset_custom += 6;
  1264. }
  1265. } else if ( customAttribute.boundTo === 'faces' ) {
  1266. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1267. value = customAttribute.value[ chunk_faces3[ f ] ];
  1268. v1 = value;
  1269. v2 = value;
  1270. v3 = value;
  1271. customAttribute.array[ offset_custom ] = v1.x;
  1272. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1273. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1274. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1275. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1276. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1277. offset_custom += 6;
  1278. }
  1279. }
  1280. } else if ( customAttribute.size === 3 ) {
  1281. var pp;
  1282. if ( customAttribute.type === 'c' ) {
  1283. pp = [ 'r', 'g', 'b' ];
  1284. } else {
  1285. pp = [ 'x', 'y', 'z' ];
  1286. }
  1287. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1288. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1289. face = obj_faces[ chunk_faces3[ f ] ];
  1290. v1 = customAttribute.value[ face.a ];
  1291. v2 = customAttribute.value[ face.b ];
  1292. v3 = customAttribute.value[ face.c ];
  1293. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1294. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1295. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1296. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1297. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1298. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1299. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1300. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1301. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1302. offset_custom += 9;
  1303. }
  1304. } else if ( customAttribute.boundTo === 'faces' ) {
  1305. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1306. value = customAttribute.value[ chunk_faces3[ f ] ];
  1307. v1 = value;
  1308. v2 = value;
  1309. v3 = value;
  1310. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1311. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1312. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1313. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1314. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1315. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1316. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1317. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1318. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1319. offset_custom += 9;
  1320. }
  1321. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  1322. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1323. value = customAttribute.value[ chunk_faces3[ f ] ];
  1324. v1 = value[ 0 ];
  1325. v2 = value[ 1 ];
  1326. v3 = value[ 2 ];
  1327. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1328. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1329. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1330. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1331. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1332. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1333. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1334. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1335. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1336. offset_custom += 9;
  1337. }
  1338. }
  1339. } else if ( customAttribute.size === 4 ) {
  1340. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  1341. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1342. face = obj_faces[ chunk_faces3[ f ] ];
  1343. v1 = customAttribute.value[ face.a ];
  1344. v2 = customAttribute.value[ face.b ];
  1345. v3 = customAttribute.value[ face.c ];
  1346. customAttribute.array[ offset_custom ] = v1.x;
  1347. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1348. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1349. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1350. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1351. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1352. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1353. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1354. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1355. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1356. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1357. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1358. offset_custom += 12;
  1359. }
  1360. } else if ( customAttribute.boundTo === 'faces' ) {
  1361. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1362. value = customAttribute.value[ chunk_faces3[ f ] ];
  1363. v1 = value;
  1364. v2 = value;
  1365. v3 = value;
  1366. customAttribute.array[ offset_custom ] = v1.x;
  1367. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1368. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1369. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1370. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1371. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1372. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1373. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1374. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1375. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1376. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1377. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1378. offset_custom += 12;
  1379. }
  1380. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  1381. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1382. value = customAttribute.value[ chunk_faces3[ f ] ];
  1383. v1 = value[ 0 ];
  1384. v2 = value[ 1 ];
  1385. v3 = value[ 2 ];
  1386. customAttribute.array[ offset_custom ] = v1.x;
  1387. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1388. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1389. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1390. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1391. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1392. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1393. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1394. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1395. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1396. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1397. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1398. offset_custom += 12;
  1399. }
  1400. }
  1401. }
  1402. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  1403. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  1404. }
  1405. }
  1406. if ( dispose ) {
  1407. delete geometryGroup.__inittedArrays;
  1408. delete geometryGroup.__colorArray;
  1409. delete geometryGroup.__normalArray;
  1410. delete geometryGroup.__tangentArray;
  1411. delete geometryGroup.__uvArray;
  1412. delete geometryGroup.__uv2Array;
  1413. delete geometryGroup.__faceArray;
  1414. delete geometryGroup.__vertexArray;
  1415. delete geometryGroup.__lineArray;
  1416. delete geometryGroup.__skinIndexArray;
  1417. delete geometryGroup.__skinWeightArray;
  1418. }
  1419. };
  1420. function setDirectBuffers( geometry, hint ) {
  1421. var attributes = geometry.attributes;
  1422. var attributeName, attributeItem;
  1423. for ( attributeName in attributes ) {
  1424. attributeItem = attributes[ attributeName ];
  1425. if ( attributeItem.needsUpdate ) {
  1426. if ( attributeName === 'index' ) {
  1427. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  1428. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  1429. } else {
  1430. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1431. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  1432. }
  1433. attributeItem.needsUpdate = false;
  1434. }
  1435. }
  1436. }
  1437. // Buffer rendering
  1438. this.renderBufferImmediate = function ( object, program, material ) {
  1439. initAttributes();
  1440. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  1441. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  1442. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  1443. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  1444. if ( object.hasPositions ) {
  1445. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  1446. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  1447. enableAttribute( program.attributes.position );
  1448. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1449. }
  1450. if ( object.hasNormals ) {
  1451. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  1452. if ( material.shading === THREE.FlatShading ) {
  1453. var nx, ny, nz,
  1454. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  1455. normalArray,
  1456. i, il = object.count * 3;
  1457. for ( i = 0; i < il; i += 9 ) {
  1458. normalArray = object.normalArray;
  1459. nax = normalArray[ i ];
  1460. nay = normalArray[ i + 1 ];
  1461. naz = normalArray[ i + 2 ];
  1462. nbx = normalArray[ i + 3 ];
  1463. nby = normalArray[ i + 4 ];
  1464. nbz = normalArray[ i + 5 ];
  1465. ncx = normalArray[ i + 6 ];
  1466. ncy = normalArray[ i + 7 ];
  1467. ncz = normalArray[ i + 8 ];
  1468. nx = ( nax + nbx + ncx ) / 3;
  1469. ny = ( nay + nby + ncy ) / 3;
  1470. nz = ( naz + nbz + ncz ) / 3;
  1471. normalArray[ i ] = nx;
  1472. normalArray[ i + 1 ] = ny;
  1473. normalArray[ i + 2 ] = nz;
  1474. normalArray[ i + 3 ] = nx;
  1475. normalArray[ i + 4 ] = ny;
  1476. normalArray[ i + 5 ] = nz;
  1477. normalArray[ i + 6 ] = nx;
  1478. normalArray[ i + 7 ] = ny;
  1479. normalArray[ i + 8 ] = nz;
  1480. }
  1481. }
  1482. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  1483. enableAttribute( program.attributes.normal );
  1484. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1485. }
  1486. if ( object.hasUvs && material.map ) {
  1487. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  1488. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  1489. enableAttribute( program.attributes.uv );
  1490. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1491. }
  1492. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  1493. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  1494. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  1495. enableAttribute( program.attributes.color );
  1496. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1497. }
  1498. disableUnusedAttributes();
  1499. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  1500. object.count = 0;
  1501. };
  1502. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  1503. for ( var attributeName in programAttributes ) {
  1504. var attributePointer = programAttributes[ attributeName ];
  1505. var attributeItem = geometryAttributes[ attributeName ];
  1506. if ( attributePointer >= 0 ) {
  1507. if ( attributeItem ) {
  1508. var attributeSize = attributeItem.itemSize;
  1509. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1510. enableAttribute( attributePointer );
  1511. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  1512. } else if ( material.defaultAttributeValues ) {
  1513. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1514. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1515. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1516. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1517. }
  1518. }
  1519. }
  1520. }
  1521. disableUnusedAttributes();
  1522. }
  1523. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  1524. if ( material.visible === false ) return;
  1525. var linewidth, a, attribute;
  1526. var attributeItem, attributeName, attributePointer, attributeSize;
  1527. var program = setProgram( camera, lights, fog, material, object );
  1528. var programAttributes = program.attributes;
  1529. var geometryAttributes = geometry.attributes;
  1530. var updateBuffers = false,
  1531. wireframeBit = material.wireframe ? 1 : 0,
  1532. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1533. if ( geometryHash !== _currentGeometryGroupHash ) {
  1534. _currentGeometryGroupHash = geometryHash;
  1535. updateBuffers = true;
  1536. }
  1537. if ( updateBuffers ) {
  1538. initAttributes();
  1539. }
  1540. // render mesh
  1541. if ( object instanceof THREE.Mesh ) {
  1542. var index = geometryAttributes[ 'index' ];
  1543. if ( index ) {
  1544. // indexed triangles
  1545. var type, size;
  1546. if ( index.array instanceof Uint32Array ) {
  1547. type = _gl.UNSIGNED_INT;
  1548. size = 4;
  1549. } else {
  1550. type = _gl.UNSIGNED_SHORT;
  1551. size = 2;
  1552. }
  1553. var offsets = geometry.offsets;
  1554. if ( offsets.length === 0 ) {
  1555. if ( updateBuffers ) {
  1556. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  1557. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1558. }
  1559. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  1560. _this.info.render.calls ++;
  1561. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  1562. _this.info.render.faces += index.array.length / 3;
  1563. } else {
  1564. // if there is more than 1 chunk
  1565. // must set attribute pointers to use new offsets for each chunk
  1566. // even if geometry and materials didn't change
  1567. updateBuffers = true;
  1568. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1569. var startIndex = offsets[ i ].index;
  1570. if ( updateBuffers ) {
  1571. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  1572. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1573. }
  1574. // render indexed triangles
  1575. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  1576. _this.info.render.calls ++;
  1577. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1578. _this.info.render.faces += offsets[ i ].count / 3;
  1579. }
  1580. }
  1581. } else {
  1582. // non-indexed triangles
  1583. if ( updateBuffers ) {
  1584. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  1585. }
  1586. var position = geometry.attributes[ 'position' ];
  1587. // render non-indexed triangles
  1588. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  1589. _this.info.render.calls ++;
  1590. _this.info.render.vertices += position.array.length / 3;
  1591. _this.info.render.faces += position.array.length / 9;
  1592. }
  1593. } else if ( object instanceof THREE.PointCloud ) {
  1594. // render particles
  1595. if ( updateBuffers ) {
  1596. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  1597. }
  1598. var position = geometryAttributes[ 'position' ];
  1599. // render particles
  1600. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  1601. _this.info.render.calls ++;
  1602. _this.info.render.points += position.array.length / 3;
  1603. } else if ( object instanceof THREE.Line ) {
  1604. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1605. setLineWidth( material.linewidth );
  1606. var index = geometryAttributes[ 'index' ];
  1607. if ( index ) {
  1608. // indexed lines
  1609. var type, size;
  1610. if ( index.array instanceof Uint32Array ) {
  1611. type = _gl.UNSIGNED_INT;
  1612. size = 4;
  1613. } else {
  1614. type = _gl.UNSIGNED_SHORT;
  1615. size = 2;
  1616. }
  1617. var offsets = geometry.offsets;
  1618. if ( offsets.length === 0 ) {
  1619. if ( updateBuffers ) {
  1620. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  1621. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1622. }
  1623. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  1624. _this.info.render.calls ++;
  1625. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  1626. } else {
  1627. // if there is more than 1 chunk
  1628. // must set attribute pointers to use new offsets for each chunk
  1629. // even if geometry and materials didn't change
  1630. if ( offsets.length > 1 ) updateBuffers = true;
  1631. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1632. var startIndex = offsets[ i ].index;
  1633. if ( updateBuffers ) {
  1634. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  1635. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1636. }
  1637. // render indexed lines
  1638. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  1639. _this.info.render.calls ++;
  1640. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1641. }
  1642. }
  1643. } else {
  1644. // non-indexed lines
  1645. if ( updateBuffers ) {
  1646. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  1647. }
  1648. var position = geometryAttributes[ 'position' ];
  1649. _gl.drawArrays( mode, 0, position.array.length / 3 );
  1650. _this.info.render.calls ++;
  1651. _this.info.render.points += position.array.length / 3;
  1652. }
  1653. }
  1654. };
  1655. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  1656. if ( material.visible === false ) return;
  1657. var linewidth, a, attribute, i, il;
  1658. var program = setProgram( camera, lights, fog, material, object );
  1659. var attributes = program.attributes;
  1660. var updateBuffers = false,
  1661. wireframeBit = material.wireframe ? 1 : 0,
  1662. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1663. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  1664. _currentGeometryGroupHash = geometryGroupHash;
  1665. updateBuffers = true;
  1666. }
  1667. if ( updateBuffers ) {
  1668. initAttributes();
  1669. }
  1670. // vertices
  1671. if ( ! material.morphTargets && attributes.position >= 0 ) {
  1672. if ( updateBuffers ) {
  1673. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1674. enableAttribute( attributes.position );
  1675. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1676. }
  1677. } else {
  1678. if ( object.morphTargetBase ) {
  1679. setupMorphTargets( material, geometryGroup, object );
  1680. }
  1681. }
  1682. if ( updateBuffers ) {
  1683. // custom attributes
  1684. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  1685. if ( geometryGroup.__webglCustomAttributesList ) {
  1686. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  1687. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  1688. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  1689. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  1690. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  1691. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  1692. }
  1693. }
  1694. }
  1695. // colors
  1696. if ( attributes.color >= 0 ) {
  1697. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  1698. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1699. enableAttribute( attributes.color );
  1700. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1701. } else if ( material.defaultAttributeValues ) {
  1702. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  1703. }
  1704. }
  1705. // normals
  1706. if ( attributes.normal >= 0 ) {
  1707. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1708. enableAttribute( attributes.normal );
  1709. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1710. }
  1711. // tangents
  1712. if ( attributes.tangent >= 0 ) {
  1713. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1714. enableAttribute( attributes.tangent );
  1715. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  1716. }
  1717. // uvs
  1718. if ( attributes.uv >= 0 ) {
  1719. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  1720. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1721. enableAttribute( attributes.uv );
  1722. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1723. } else if ( material.defaultAttributeValues ) {
  1724. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  1725. }
  1726. }
  1727. if ( attributes.uv2 >= 0 ) {
  1728. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  1729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1730. enableAttribute( attributes.uv2 );
  1731. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  1732. } else if ( material.defaultAttributeValues ) {
  1733. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  1734. }
  1735. }
  1736. if ( material.skinning &&
  1737. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  1738. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1739. enableAttribute( attributes.skinIndex );
  1740. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  1741. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1742. enableAttribute( attributes.skinWeight );
  1743. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  1744. }
  1745. // line distances
  1746. if ( attributes.lineDistance >= 0 ) {
  1747. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  1748. enableAttribute( attributes.lineDistance );
  1749. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  1750. }
  1751. }
  1752. disableUnusedAttributes();
  1753. // render mesh
  1754. if ( object instanceof THREE.Mesh ) {
  1755. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  1756. // wireframe
  1757. if ( material.wireframe ) {
  1758. setLineWidth( material.wireframeLinewidth );
  1759. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1760. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  1761. // triangles
  1762. } else {
  1763. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1764. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  1765. }
  1766. _this.info.render.calls ++;
  1767. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  1768. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  1769. // render lines
  1770. } else if ( object instanceof THREE.Line ) {
  1771. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1772. setLineWidth( material.linewidth );
  1773. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  1774. _this.info.render.calls ++;
  1775. // render particles
  1776. } else if ( object instanceof THREE.PointCloud ) {
  1777. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  1778. _this.info.render.calls ++;
  1779. _this.info.render.points += geometryGroup.__webglParticleCount;
  1780. }
  1781. };
  1782. function initAttributes() {
  1783. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  1784. _newAttributes[ i ] = 0;
  1785. }
  1786. }
  1787. function enableAttribute( attribute ) {
  1788. _newAttributes[ attribute ] = 1;
  1789. if ( _enabledAttributes[ attribute ] === 0 ) {
  1790. _gl.enableVertexAttribArray( attribute );
  1791. _enabledAttributes[ attribute ] = 1;
  1792. }
  1793. }
  1794. function disableUnusedAttributes() {
  1795. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  1796. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  1797. _gl.disableVertexAttribArray( i );
  1798. _enabledAttributes[ i ] = 0;
  1799. }
  1800. }
  1801. }
  1802. function setupMorphTargets ( material, geometryGroup, object ) {
  1803. // set base
  1804. var attributes = material.program.attributes;
  1805. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  1806. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  1807. enableAttribute( attributes.position );
  1808. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1809. } else if ( attributes.position >= 0 ) {
  1810. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1811. enableAttribute( attributes.position );
  1812. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1813. }
  1814. if ( object.morphTargetForcedOrder.length ) {
  1815. // set forced order
  1816. var m = 0;
  1817. var order = object.morphTargetForcedOrder;
  1818. var influences = object.morphTargetInfluences;
  1819. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  1820. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  1821. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  1822. enableAttribute( attributes[ 'morphTarget' + m ] );
  1823. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  1824. }
  1825. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  1826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  1827. enableAttribute( attributes[ 'morphNormal' + m ] );
  1828. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  1829. }
  1830. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  1831. m ++;
  1832. }
  1833. } else {
  1834. // find the most influencing
  1835. var influence, activeInfluenceIndices = [];
  1836. var influences = object.morphTargetInfluences;
  1837. var i, il = influences.length;
  1838. for ( i = 0; i < il; i ++ ) {
  1839. influence = influences[ i ];
  1840. if ( influence > 0 ) {
  1841. activeInfluenceIndices.push( [ influence, i ] );
  1842. }
  1843. }
  1844. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  1845. activeInfluenceIndices.sort( numericalSort );
  1846. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  1847. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  1848. activeInfluenceIndices.sort( numericalSort );
  1849. } else if ( activeInfluenceIndices.length === 0 ) {
  1850. activeInfluenceIndices.push( [ 0, 0 ] );
  1851. };
  1852. var influenceIndex, m = 0;
  1853. while ( m < material.numSupportedMorphTargets ) {
  1854. if ( activeInfluenceIndices[ m ] ) {
  1855. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  1856. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  1857. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  1858. enableAttribute( attributes[ 'morphTarget' + m ] );
  1859. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  1860. }
  1861. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  1862. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  1863. enableAttribute( attributes[ 'morphNormal' + m ] );
  1864. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  1865. }
  1866. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  1867. } else {
  1868. /*
  1869. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1870. if ( material.morphNormals ) {
  1871. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1872. }
  1873. */
  1874. object.__webglMorphTargetInfluences[ m ] = 0;
  1875. }
  1876. m ++;
  1877. }
  1878. }
  1879. // load updated influences uniform
  1880. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  1881. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  1882. }
  1883. };
  1884. // Sorting
  1885. function painterSortStable ( a, b ) {
  1886. if ( a.z !== b.z ) {
  1887. return b.z - a.z;
  1888. } else {
  1889. return a.id - b.id;
  1890. }
  1891. };
  1892. function reversePainterSortStable ( a, b ) {
  1893. if ( a.z !== b.z ) {
  1894. return a.z - b.z;
  1895. } else {
  1896. return a.id - b.id;
  1897. }
  1898. };
  1899. function numericalSort ( a, b ) {
  1900. return b[ 0 ] - a[ 0 ];
  1901. };
  1902. // Rendering
  1903. this.render = function ( scene, camera, renderTarget, forceClear ) {
  1904. if ( camera instanceof THREE.Camera === false ) {
  1905. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  1906. return;
  1907. }
  1908. var i, il,
  1909. webglObject, object,
  1910. renderList,
  1911. lights = scene.__lights,
  1912. fog = scene.fog;
  1913. // reset caching for this frame
  1914. _currentMaterialId = - 1;
  1915. _lightsNeedUpdate = true;
  1916. // update scene graph
  1917. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  1918. // update camera matrices and frustum
  1919. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  1920. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1921. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  1922. _frustum.setFromMatrix( _projScreenMatrix );
  1923. // update WebGL objects
  1924. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  1925. // custom render plugins (pre pass)
  1926. renderPlugins( this.renderPluginsPre, scene, camera );
  1927. //
  1928. _this.info.render.calls = 0;
  1929. _this.info.render.vertices = 0;
  1930. _this.info.render.faces = 0;
  1931. _this.info.render.points = 0;
  1932. this.setRenderTarget( renderTarget );
  1933. if ( this.autoClear || forceClear ) {
  1934. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  1935. }
  1936. // set matrices for regular objects (frustum culled)
  1937. opaqueObjects.length = 0;
  1938. transparentObjects.length = 0;
  1939. _sortObjects = this.sortObjects;
  1940. projectObject(scene,scene,camera);
  1941. if ( this.sortObjects ) {
  1942. opaqueObjects.sort( painterSortStable );
  1943. transparentObjects.sort( reversePainterSortStable );
  1944. }
  1945. // set matrices for immediate objects
  1946. renderList = scene.__webglObjectsImmediate;
  1947. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  1948. webglObject = renderList[ i ];
  1949. object = webglObject.object;
  1950. if ( object.visible ) {
  1951. setupMatrices( object, camera );
  1952. unrollImmediateBufferMaterial( webglObject );
  1953. }
  1954. }
  1955. if ( scene.overrideMaterial ) {
  1956. var material = scene.overrideMaterial;
  1957. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  1958. this.setDepthTest( material.depthTest );
  1959. this.setDepthWrite( material.depthWrite );
  1960. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  1961. renderObjects( opaqueObjects, camera, lights, fog, true, material );
  1962. renderObjects( transparentObjects, camera, lights, fog, true, material );
  1963. renderObjectsImmediate( scene.__webglObjectsImmediate, '', camera, lights, fog, false, material );
  1964. } else {
  1965. var material = null;
  1966. // opaque pass (front-to-back order)
  1967. this.setBlending( THREE.NoBlending );
  1968. renderObjects( opaqueObjects, camera, lights, fog, false, material );
  1969. renderObjectsImmediate( scene.__webglObjectsImmediate, 'opaque', camera, lights, fog, false, material );
  1970. // transparent pass (back-to-front order)
  1971. renderObjects( transparentObjects, camera, lights, fog, true, material );
  1972. renderObjectsImmediate( scene.__webglObjectsImmediate, 'transparent', camera, lights, fog, true, material );
  1973. }
  1974. // custom render plugins (post pass)
  1975. renderPlugins( this.renderPluginsPost, scene, camera );
  1976. // Generate mipmap if we're using any kind of mipmap filtering
  1977. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  1978. updateRenderTargetMipmap( renderTarget );
  1979. }
  1980. // Ensure depth buffer writing is enabled so it can be cleared on next render
  1981. this.setDepthTest( true );
  1982. this.setDepthWrite( true );
  1983. // _gl.finish();
  1984. };
  1985. function projectObject(scene, object,camera){
  1986. if ( object.visible ) {
  1987. var webglObjects = scene.__webglObjects[object.id];
  1988. if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  1989. updateObject(scene, object);
  1990. setupMatrices( object, camera );
  1991. for (var i = 0, l = webglObjects.length; i < l; i++){
  1992. var webglObject = webglObjects[i];
  1993. unrollBufferMaterial( webglObject );
  1994. webglObject.render = true;
  1995. if ( _sortObjects === true ) {
  1996. if ( object.renderDepth !== null ) {
  1997. webglObject.z = object.renderDepth;
  1998. } else {
  1999. _vector3.setFromMatrixPosition( object.matrixWorld );
  2000. _vector3.applyProjection( _projScreenMatrix );
  2001. webglObject.z = _vector3.z;
  2002. }
  2003. }
  2004. }
  2005. }
  2006. for(var i = 0, l = object.children.length; i < l; i++) {
  2007. projectObject(scene, object.children[i],camera);
  2008. }
  2009. }
  2010. }
  2011. function renderPlugins( plugins, scene, camera ) {
  2012. if ( ! plugins.length ) return;
  2013. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  2014. // reset state for plugin (to start from clean slate)
  2015. _currentProgram = null;
  2016. _currentCamera = null;
  2017. _oldBlending = - 1;
  2018. _oldDepthTest = - 1;
  2019. _oldDepthWrite = - 1;
  2020. _oldDoubleSided = - 1;
  2021. _oldFlipSided = - 1;
  2022. _currentGeometryGroupHash = - 1;
  2023. _currentMaterialId = - 1;
  2024. _lightsNeedUpdate = true;
  2025. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  2026. // reset state after plugin (anything could have changed)
  2027. _currentProgram = null;
  2028. _currentCamera = null;
  2029. _oldBlending = - 1;
  2030. _oldDepthTest = - 1;
  2031. _oldDepthWrite = - 1;
  2032. _oldDoubleSided = - 1;
  2033. _oldFlipSided = - 1;
  2034. _currentGeometryGroupHash = - 1;
  2035. _currentMaterialId = - 1;
  2036. _lightsNeedUpdate = true;
  2037. }
  2038. };
  2039. function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) {
  2040. var webglObject, object, buffer, material;
  2041. for ( var i = renderList.length - 1; i !== - 1; i -- ) {
  2042. webglObject = renderList[ i ];
  2043. object = webglObject.object;
  2044. buffer = webglObject.buffer;
  2045. if ( overrideMaterial ) {
  2046. material = overrideMaterial;
  2047. } else {
  2048. material = webglObject.material;
  2049. if ( ! material ) continue;
  2050. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2051. _this.setDepthTest( material.depthTest );
  2052. _this.setDepthWrite( material.depthWrite );
  2053. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2054. }
  2055. _this.setMaterialFaces( material );
  2056. if ( buffer instanceof THREE.BufferGeometry ) {
  2057. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  2058. } else {
  2059. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  2060. }
  2061. }
  2062. };
  2063. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2064. var webglObject, object, material, program;
  2065. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  2066. webglObject = renderList[ i ];
  2067. object = webglObject.object;
  2068. if ( object.visible ) {
  2069. if ( overrideMaterial ) {
  2070. material = overrideMaterial;
  2071. } else {
  2072. material = webglObject[ materialType ];
  2073. if ( ! material ) continue;
  2074. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2075. _this.setDepthTest( material.depthTest );
  2076. _this.setDepthWrite( material.depthWrite );
  2077. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2078. }
  2079. _this.renderImmediateObject( camera, lights, fog, material, object );
  2080. }
  2081. }
  2082. };
  2083. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  2084. var program = setProgram( camera, lights, fog, material, object );
  2085. _currentGeometryGroupHash = - 1;
  2086. _this.setMaterialFaces( material );
  2087. if ( object.immediateRenderCallback ) {
  2088. object.immediateRenderCallback( program, _gl, _frustum );
  2089. } else {
  2090. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  2091. }
  2092. };
  2093. function unrollImmediateBufferMaterial ( globject ) {
  2094. var object = globject.object,
  2095. material = object.material;
  2096. if ( material.transparent ) {
  2097. globject.transparent = material;
  2098. globject.opaque = null;
  2099. } else {
  2100. globject.opaque = material;
  2101. globject.transparent = null;
  2102. }
  2103. };
  2104. function unrollBufferMaterial ( globject ) {
  2105. var object = globject.object;
  2106. var buffer = globject.buffer;
  2107. var geometry = object.geometry;
  2108. var material = object.material;
  2109. if ( material instanceof THREE.MeshFaceMaterial ) {
  2110. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  2111. material = material.materials[ materialIndex ];
  2112. if ( material.transparent ) {
  2113. globject.material = material;
  2114. transparentObjects.push(globject);
  2115. } else {
  2116. globject.material = material;
  2117. opaqueObjects.push(globject);
  2118. }
  2119. } else {
  2120. if ( material ) {
  2121. if ( material.transparent ) {
  2122. globject.material = material;
  2123. transparentObjects.push(globject);
  2124. } else {
  2125. globject.material = material;
  2126. opaqueObjects.push(globject);
  2127. }
  2128. }
  2129. }
  2130. };
  2131. // Objects refresh
  2132. this.initWebGLObjects = function ( scene ) {
  2133. if ( ! scene.__webglObjects ) {
  2134. scene.__webglObjects = {};
  2135. scene.__webglObjectsImmediate = [];
  2136. scene.__webglSprites = [];
  2137. scene.__webglFlares = [];
  2138. }
  2139. while ( scene.__objectsAdded.length ) {
  2140. addObject( scene.__objectsAdded[ 0 ], scene );
  2141. scene.__objectsAdded.splice( 0, 1 );
  2142. }
  2143. while ( scene.__objectsRemoved.length ) {
  2144. removeObject( scene.__objectsRemoved[ 0 ], scene );
  2145. scene.__objectsRemoved.splice( 0, 1 );
  2146. }
  2147. };
  2148. // Objects adding
  2149. function addObject( object, scene ) {
  2150. var g, geometry, geometryGroup;
  2151. if ( object.__webglInit === undefined ) {
  2152. object.__webglInit = true;
  2153. object._modelViewMatrix = new THREE.Matrix4();
  2154. object._normalMatrix = new THREE.Matrix3();
  2155. }
  2156. geometry = object.geometry;
  2157. if ( geometry === undefined ) {
  2158. // ImmediateRenderObject
  2159. } else if ( geometry.__webglInit === undefined ) {
  2160. geometry.__webglInit = true;
  2161. geometry.addEventListener( 'dispose', onGeometryDispose );
  2162. if ( geometry instanceof THREE.BufferGeometry ) {
  2163. initDirectBuffers( geometry );
  2164. } else if ( object instanceof THREE.Mesh ) {
  2165. if ( object.__webglActive !== undefined ) {
  2166. removeObject( object, scene );
  2167. }
  2168. initGeometryGroups(scene, object, geometry);
  2169. } else if ( object instanceof THREE.Line ) {
  2170. if ( ! geometry.__webglVertexBuffer ) {
  2171. createLineBuffers( geometry );
  2172. initLineBuffers( geometry, object );
  2173. geometry.verticesNeedUpdate = true;
  2174. geometry.colorsNeedUpdate = true;
  2175. geometry.lineDistancesNeedUpdate = true;
  2176. }
  2177. } else if ( object instanceof THREE.PointCloud ) {
  2178. if ( ! geometry.__webglVertexBuffer ) {
  2179. createParticleBuffers( geometry );
  2180. initParticleBuffers( geometry, object );
  2181. geometry.verticesNeedUpdate = true;
  2182. geometry.colorsNeedUpdate = true;
  2183. }
  2184. }
  2185. }
  2186. if ( object.__webglActive === undefined) {
  2187. if ( object instanceof THREE.Mesh ) {
  2188. geometry = object.geometry;
  2189. if ( geometry instanceof THREE.BufferGeometry ) {
  2190. addBuffer( scene.__webglObjects, geometry, object );
  2191. } else if ( geometry instanceof THREE.Geometry ) {
  2192. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  2193. geometryGroup = geometry.geometryGroupsList[ i ];
  2194. addBuffer( scene.__webglObjects, geometryGroup, object );
  2195. }
  2196. }
  2197. } else if ( object instanceof THREE.Line ||
  2198. object instanceof THREE.PointCloud ) {
  2199. geometry = object.geometry;
  2200. addBuffer( scene.__webglObjects, geometry, object );
  2201. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2202. addBufferImmediate( scene.__webglObjectsImmediate, object );
  2203. } else if ( object instanceof THREE.Sprite ) {
  2204. scene.__webglSprites.push( object );
  2205. } else if ( object instanceof THREE.LensFlare ) {
  2206. scene.__webglFlares.push( object );
  2207. }
  2208. object.__webglActive = true;
  2209. }
  2210. };
  2211. function initGeometryGroups(scene,object,geometry) {
  2212. var g, geometryGroup, material,addBuffers = false;
  2213. material = object.material;
  2214. if ( geometry.geometryGroups === undefined ) {
  2215. delete scene.__webglObjects[object.id];
  2216. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  2217. }
  2218. // create separate VBOs per geometry chunk
  2219. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  2220. geometryGroup = geometry.geometryGroupsList[ i ];
  2221. // initialise VBO on the first access
  2222. if ( ! geometryGroup.__webglVertexBuffer ) {
  2223. createMeshBuffers( geometryGroup );
  2224. initMeshBuffers( geometryGroup, object );
  2225. geometry.verticesNeedUpdate = true;
  2226. geometry.morphTargetsNeedUpdate = true;
  2227. geometry.elementsNeedUpdate = true;
  2228. geometry.uvsNeedUpdate = true;
  2229. geometry.normalsNeedUpdate = true;
  2230. geometry.tangentsNeedUpdate = true;
  2231. geometry.colorsNeedUpdate = true;
  2232. addBuffers = true;
  2233. } else {
  2234. addBuffers = false;
  2235. }
  2236. if ( addBuffers || object.__webglActive === undefined ) {
  2237. addBuffer( scene.__webglObjects, geometryGroup, object );
  2238. }
  2239. }
  2240. object.__webglActive = true;
  2241. }
  2242. function addBuffer( objlist, buffer, object ) {
  2243. var id = object.id;
  2244. objlist[id] = objlist[id] || [];
  2245. objlist[id].push(
  2246. {
  2247. id: null,
  2248. buffer: buffer,
  2249. object: object,
  2250. material: null,
  2251. z: 0
  2252. }
  2253. );
  2254. };
  2255. function addBufferImmediate( objlist, object ) {
  2256. objlist.push(
  2257. {
  2258. id: null,
  2259. object: object,
  2260. opaque: null,
  2261. transparent: null,
  2262. z: 0
  2263. }
  2264. );
  2265. };
  2266. // Objects updates
  2267. function updateObject(scene, object ) {
  2268. var geometry = object.geometry,
  2269. geometryGroup, customAttributesDirty, material;
  2270. if ( geometry instanceof THREE.BufferGeometry ) {
  2271. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  2272. } else if ( object instanceof THREE.Mesh ) {
  2273. // check all geometry groups
  2274. if ( geometry.buffersNeedUpdate ) {
  2275. if ( geometry instanceof THREE.BufferGeometry ) {
  2276. initDirectBuffers( geometry );
  2277. } else if ( object instanceof THREE.Mesh ) {
  2278. initGeometryGroups(scene, object,geometry);
  2279. }
  2280. }
  2281. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  2282. geometryGroup = geometry.geometryGroupsList[ i ];
  2283. material = getBufferMaterial( object, geometryGroup );
  2284. if ( geometry.buffersNeedUpdate ) {
  2285. initMeshBuffers( geometryGroup, object );
  2286. }
  2287. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2288. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  2289. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  2290. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  2291. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  2292. }
  2293. }
  2294. geometry.verticesNeedUpdate = false;
  2295. geometry.morphTargetsNeedUpdate = false;
  2296. geometry.elementsNeedUpdate = false;
  2297. geometry.uvsNeedUpdate = false;
  2298. geometry.normalsNeedUpdate = false;
  2299. geometry.colorsNeedUpdate = false;
  2300. geometry.tangentsNeedUpdate = false;
  2301. geometry.buffersNeedUpdate = false;
  2302. material.attributes && clearCustomAttributes( material );
  2303. } else if ( object instanceof THREE.Line ) {
  2304. material = getBufferMaterial( object, geometry );
  2305. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2306. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  2307. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  2308. }
  2309. geometry.verticesNeedUpdate = false;
  2310. geometry.colorsNeedUpdate = false;
  2311. geometry.lineDistancesNeedUpdate = false;
  2312. material.attributes && clearCustomAttributes( material );
  2313. } else if ( object instanceof THREE.PointCloud ) {
  2314. material = getBufferMaterial( object, geometry );
  2315. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2316. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  2317. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  2318. }
  2319. geometry.verticesNeedUpdate = false;
  2320. geometry.colorsNeedUpdate = false;
  2321. material.attributes && clearCustomAttributes( material );
  2322. }
  2323. };
  2324. // Objects updates - custom attributes check
  2325. function areCustomAttributesDirty( material ) {
  2326. for ( var a in material.attributes ) {
  2327. if ( material.attributes[ a ].needsUpdate ) return true;
  2328. }
  2329. return false;
  2330. };
  2331. function clearCustomAttributes( material ) {
  2332. for ( var a in material.attributes ) {
  2333. material.attributes[ a ].needsUpdate = false;
  2334. }
  2335. };
  2336. // Objects removal
  2337. function removeObject( object, scene ) {
  2338. if ( object instanceof THREE.Mesh ||
  2339. object instanceof THREE.PointCloud ||
  2340. object instanceof THREE.Line ) {
  2341. removeInstancesWebglObjects( scene.__webglObjects, object );
  2342. } else if ( object instanceof THREE.Sprite ) {
  2343. removeInstancesDirect( scene.__webglSprites, object );
  2344. } else if ( object instanceof THREE.LensFlare ) {
  2345. removeInstancesDirect( scene.__webglFlares, object );
  2346. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2347. removeInstances( scene.__webglObjectsImmediate, object );
  2348. }
  2349. delete object.__webglActive;
  2350. };
  2351. function removeInstancesWebglObjects( objlist, object ) {
  2352. delete objlist[object];
  2353. };
  2354. function removeInstances( objlist, object ) {
  2355. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2356. if ( objlist[ o ].object === object ) {
  2357. objlist.splice( o, 1 );
  2358. }
  2359. }
  2360. };
  2361. function removeInstancesDirect( objlist, object ) {
  2362. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2363. if ( objlist[ o ] === object ) {
  2364. objlist.splice( o, 1 );
  2365. }
  2366. }
  2367. };
  2368. // Materials
  2369. this.initMaterial = function ( material, lights, fog, object ) {
  2370. material.addEventListener( 'dispose', onMaterialDispose );
  2371. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  2372. if ( material instanceof THREE.MeshDepthMaterial ) {
  2373. shaderID = 'depth';
  2374. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2375. shaderID = 'normal';
  2376. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  2377. shaderID = 'basic';
  2378. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2379. shaderID = 'lambert';
  2380. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2381. shaderID = 'phong';
  2382. } else if ( material instanceof THREE.LineBasicMaterial ) {
  2383. shaderID = 'basic';
  2384. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2385. shaderID = 'dashed';
  2386. } else if ( material instanceof THREE.PointCloudMaterial ) {
  2387. shaderID = 'particle_basic';
  2388. }
  2389. if ( shaderID ) {
  2390. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  2391. }
  2392. // heuristics to create shader parameters according to lights in the scene
  2393. // (not to blow over maxLights budget)
  2394. maxLightCount = allocateLights( lights );
  2395. maxShadows = allocateShadows( lights );
  2396. maxBones = allocateBones( object );
  2397. parameters = {
  2398. precision: _precision,
  2399. supportsVertexTextures: _supportsVertexTextures,
  2400. map: !! material.map,
  2401. envMap: !! material.envMap,
  2402. lightMap: !! material.lightMap,
  2403. bumpMap: !! material.bumpMap,
  2404. normalMap: !! material.normalMap,
  2405. specularMap: !! material.specularMap,
  2406. vertexColors: material.vertexColors,
  2407. fog: fog,
  2408. useFog: material.fog,
  2409. fogExp: fog instanceof THREE.FogExp2,
  2410. sizeAttenuation: material.sizeAttenuation,
  2411. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  2412. skinning: material.skinning,
  2413. maxBones: maxBones,
  2414. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  2415. morphTargets: material.morphTargets,
  2416. morphNormals: material.morphNormals,
  2417. maxMorphTargets: this.maxMorphTargets,
  2418. maxMorphNormals: this.maxMorphNormals,
  2419. maxDirLights: maxLightCount.directional,
  2420. maxPointLights: maxLightCount.point,
  2421. maxSpotLights: maxLightCount.spot,
  2422. maxHemiLights: maxLightCount.hemi,
  2423. maxShadows: maxShadows,
  2424. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  2425. shadowMapType: this.shadowMapType,
  2426. shadowMapDebug: this.shadowMapDebug,
  2427. shadowMapCascade: this.shadowMapCascade,
  2428. alphaTest: material.alphaTest,
  2429. metal: material.metal,
  2430. wrapAround: material.wrapAround,
  2431. doubleSided: material.side === THREE.DoubleSide,
  2432. flipSided: material.side === THREE.BackSide
  2433. };
  2434. // Generate code
  2435. var chunks = [];
  2436. if ( shaderID ) {
  2437. chunks.push( shaderID );
  2438. } else {
  2439. chunks.push( material.fragmentShader );
  2440. chunks.push( material.vertexShader );
  2441. }
  2442. for ( var d in material.defines ) {
  2443. chunks.push( d );
  2444. chunks.push( material.defines[ d ] );
  2445. }
  2446. for ( var p in parameters ) {
  2447. chunks.push( p );
  2448. chunks.push( parameters[ p ] );
  2449. }
  2450. var code = chunks.join();
  2451. var program;
  2452. // Check if code has been already compiled
  2453. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  2454. var programInfo = _programs[ p ];
  2455. if ( programInfo.code === code ) {
  2456. program = programInfo;
  2457. program.usedTimes ++;
  2458. break;
  2459. }
  2460. }
  2461. if ( program === undefined ) {
  2462. program = new THREE.WebGLProgram( this, code, material, parameters );
  2463. _programs.push( program );
  2464. _this.info.memory.programs = _programs.length;
  2465. }
  2466. material.program = program;
  2467. var attributes = material.program.attributes;
  2468. if ( material.morphTargets ) {
  2469. material.numSupportedMorphTargets = 0;
  2470. var id, base = 'morphTarget';
  2471. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  2472. id = base + i;
  2473. if ( attributes[ id ] >= 0 ) {
  2474. material.numSupportedMorphTargets ++;
  2475. }
  2476. }
  2477. }
  2478. if ( material.morphNormals ) {
  2479. material.numSupportedMorphNormals = 0;
  2480. var id, base = 'morphNormal';
  2481. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  2482. id = base + i;
  2483. if ( attributes[ id ] >= 0 ) {
  2484. material.numSupportedMorphNormals ++;
  2485. }
  2486. }
  2487. }
  2488. material.uniformsList = [];
  2489. for ( u in material.uniforms ) {
  2490. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  2491. }
  2492. };
  2493. function setMaterialShaders( material, shaders ) {
  2494. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  2495. material.vertexShader = shaders.vertexShader;
  2496. material.fragmentShader = shaders.fragmentShader;
  2497. };
  2498. function setProgram( camera, lights, fog, material, object ) {
  2499. _usedTextureUnits = 0;
  2500. if ( material.needsUpdate ) {
  2501. if ( material.program ) deallocateMaterial( material );
  2502. _this.initMaterial( material, lights, fog, object );
  2503. material.needsUpdate = false;
  2504. }
  2505. if ( material.morphTargets ) {
  2506. if ( ! object.__webglMorphTargetInfluences ) {
  2507. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  2508. }
  2509. }
  2510. var refreshMaterial = false;
  2511. var program = material.program,
  2512. p_uniforms = program.uniforms,
  2513. m_uniforms = material.uniforms;
  2514. if ( program.id !== _currentProgram ) {
  2515. _gl.useProgram( program.program );
  2516. _currentProgram = program.id;
  2517. refreshMaterial = true;
  2518. }
  2519. if ( material.id !== _currentMaterialId ) {
  2520. _currentMaterialId = material.id;
  2521. refreshMaterial = true;
  2522. }
  2523. if ( refreshMaterial || camera !== _currentCamera ) {
  2524. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2525. if ( _logarithmicDepthBuffer ) {
  2526. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  2527. }
  2528. if ( camera !== _currentCamera ) _currentCamera = camera;
  2529. }
  2530. // skinning uniforms must be set even if material didn't change
  2531. // auto-setting of texture unit for bone texture must go before other textures
  2532. // not sure why, but otherwise weird things happen
  2533. if ( material.skinning ) {
  2534. if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) {
  2535. if ( p_uniforms.boneTexture !== null ) {
  2536. var textureUnit = getTextureUnit();
  2537. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  2538. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  2539. }
  2540. if ( p_uniforms.boneTextureWidth !== null ) {
  2541. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  2542. }
  2543. if ( p_uniforms.boneTextureHeight !== null ) {
  2544. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  2545. }
  2546. } else {
  2547. if ( p_uniforms.boneGlobalMatrices !== null ) {
  2548. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  2549. }
  2550. }
  2551. }
  2552. if ( refreshMaterial ) {
  2553. // refresh uniforms common to several materials
  2554. if ( fog && material.fog ) {
  2555. refreshUniformsFog( m_uniforms, fog );
  2556. }
  2557. if ( material instanceof THREE.MeshPhongMaterial ||
  2558. material instanceof THREE.MeshLambertMaterial ||
  2559. material.lights ) {
  2560. if ( _lightsNeedUpdate ) {
  2561. setupLights( program, lights );
  2562. _lightsNeedUpdate = false;
  2563. }
  2564. refreshUniformsLights( m_uniforms, _lights );
  2565. }
  2566. if ( material instanceof THREE.MeshBasicMaterial ||
  2567. material instanceof THREE.MeshLambertMaterial ||
  2568. material instanceof THREE.MeshPhongMaterial ) {
  2569. refreshUniformsCommon( m_uniforms, material );
  2570. }
  2571. // refresh single material specific uniforms
  2572. if ( material instanceof THREE.LineBasicMaterial ) {
  2573. refreshUniformsLine( m_uniforms, material );
  2574. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2575. refreshUniformsLine( m_uniforms, material );
  2576. refreshUniformsDash( m_uniforms, material );
  2577. } else if ( material instanceof THREE.PointCloudMaterial ) {
  2578. refreshUniformsParticle( m_uniforms, material );
  2579. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2580. refreshUniformsPhong( m_uniforms, material );
  2581. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2582. refreshUniformsLambert( m_uniforms, material );
  2583. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  2584. m_uniforms.mNear.value = camera.near;
  2585. m_uniforms.mFar.value = camera.far;
  2586. m_uniforms.opacity.value = material.opacity;
  2587. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2588. m_uniforms.opacity.value = material.opacity;
  2589. }
  2590. if ( object.receiveShadow && ! material._shadowPass ) {
  2591. refreshUniformsShadow( m_uniforms, lights );
  2592. }
  2593. // load common uniforms
  2594. loadUniformsGeneric( program, material.uniformsList );
  2595. // load material specific uniforms
  2596. // (shader material also gets them for the sake of genericity)
  2597. if ( material instanceof THREE.ShaderMaterial ||
  2598. material instanceof THREE.MeshPhongMaterial ||
  2599. material.envMap ) {
  2600. if ( p_uniforms.cameraPosition !== null ) {
  2601. _vector3.setFromMatrixPosition( camera.matrixWorld );
  2602. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  2603. }
  2604. }
  2605. if ( material instanceof THREE.MeshPhongMaterial ||
  2606. material instanceof THREE.MeshLambertMaterial ||
  2607. material instanceof THREE.ShaderMaterial ||
  2608. material.skinning ) {
  2609. if ( p_uniforms.viewMatrix !== null ) {
  2610. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  2611. }
  2612. }
  2613. }
  2614. loadUniformsMatrices( p_uniforms, object );
  2615. if ( p_uniforms.modelMatrix !== null ) {
  2616. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  2617. }
  2618. return program;
  2619. };
  2620. // Uniforms (refresh uniforms objects)
  2621. function refreshUniformsCommon ( uniforms, material ) {
  2622. uniforms.opacity.value = material.opacity;
  2623. if ( _this.gammaInput ) {
  2624. uniforms.diffuse.value.copyGammaToLinear( material.color );
  2625. } else {
  2626. uniforms.diffuse.value = material.color;
  2627. }
  2628. uniforms.map.value = material.map;
  2629. uniforms.lightMap.value = material.lightMap;
  2630. uniforms.specularMap.value = material.specularMap;
  2631. if ( material.bumpMap ) {
  2632. uniforms.bumpMap.value = material.bumpMap;
  2633. uniforms.bumpScale.value = material.bumpScale;
  2634. }
  2635. if ( material.normalMap ) {
  2636. uniforms.normalMap.value = material.normalMap;
  2637. uniforms.normalScale.value.copy( material.normalScale );
  2638. }
  2639. // uv repeat and offset setting priorities
  2640. // 1. color map
  2641. // 2. specular map
  2642. // 3. normal map
  2643. // 4. bump map
  2644. var uvScaleMap;
  2645. if ( material.map ) {
  2646. uvScaleMap = material.map;
  2647. } else if ( material.specularMap ) {
  2648. uvScaleMap = material.specularMap;
  2649. } else if ( material.normalMap ) {
  2650. uvScaleMap = material.normalMap;
  2651. } else if ( material.bumpMap ) {
  2652. uvScaleMap = material.bumpMap;
  2653. }
  2654. if ( uvScaleMap !== undefined ) {
  2655. var offset = uvScaleMap.offset;
  2656. var repeat = uvScaleMap.repeat;
  2657. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  2658. }
  2659. uniforms.envMap.value = material.envMap;
  2660. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  2661. if ( _this.gammaInput ) {
  2662. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  2663. uniforms.reflectivity.value = material.reflectivity;
  2664. } else {
  2665. uniforms.reflectivity.value = material.reflectivity;
  2666. }
  2667. uniforms.refractionRatio.value = material.refractionRatio;
  2668. uniforms.combine.value = material.combine;
  2669. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  2670. };
  2671. function refreshUniformsLine ( uniforms, material ) {
  2672. uniforms.diffuse.value = material.color;
  2673. uniforms.opacity.value = material.opacity;
  2674. };
  2675. function refreshUniformsDash ( uniforms, material ) {
  2676. uniforms.dashSize.value = material.dashSize;
  2677. uniforms.totalSize.value = material.dashSize + material.gapSize;
  2678. uniforms.scale.value = material.scale;
  2679. };
  2680. function refreshUniformsParticle ( uniforms, material ) {
  2681. uniforms.psColor.value = material.color;
  2682. uniforms.opacity.value = material.opacity;
  2683. uniforms.size.value = material.size;
  2684. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  2685. uniforms.map.value = material.map;
  2686. };
  2687. function refreshUniformsFog ( uniforms, fog ) {
  2688. uniforms.fogColor.value = fog.color;
  2689. if ( fog instanceof THREE.Fog ) {
  2690. uniforms.fogNear.value = fog.near;
  2691. uniforms.fogFar.value = fog.far;
  2692. } else if ( fog instanceof THREE.FogExp2 ) {
  2693. uniforms.fogDensity.value = fog.density;
  2694. }
  2695. };
  2696. function refreshUniformsPhong ( uniforms, material ) {
  2697. uniforms.shininess.value = material.shininess;
  2698. if ( _this.gammaInput ) {
  2699. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2700. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2701. uniforms.specular.value.copyGammaToLinear( material.specular );
  2702. } else {
  2703. uniforms.ambient.value = material.ambient;
  2704. uniforms.emissive.value = material.emissive;
  2705. uniforms.specular.value = material.specular;
  2706. }
  2707. if ( material.wrapAround ) {
  2708. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2709. }
  2710. };
  2711. function refreshUniformsLambert ( uniforms, material ) {
  2712. if ( _this.gammaInput ) {
  2713. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2714. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2715. } else {
  2716. uniforms.ambient.value = material.ambient;
  2717. uniforms.emissive.value = material.emissive;
  2718. }
  2719. if ( material.wrapAround ) {
  2720. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2721. }
  2722. };
  2723. function refreshUniformsLights ( uniforms, lights ) {
  2724. uniforms.ambientLightColor.value = lights.ambient;
  2725. uniforms.directionalLightColor.value = lights.directional.colors;
  2726. uniforms.directionalLightDirection.value = lights.directional.positions;
  2727. uniforms.pointLightColor.value = lights.point.colors;
  2728. uniforms.pointLightPosition.value = lights.point.positions;
  2729. uniforms.pointLightDistance.value = lights.point.distances;
  2730. uniforms.spotLightColor.value = lights.spot.colors;
  2731. uniforms.spotLightPosition.value = lights.spot.positions;
  2732. uniforms.spotLightDistance.value = lights.spot.distances;
  2733. uniforms.spotLightDirection.value = lights.spot.directions;
  2734. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  2735. uniforms.spotLightExponent.value = lights.spot.exponents;
  2736. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  2737. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  2738. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  2739. };
  2740. function refreshUniformsShadow ( uniforms, lights ) {
  2741. if ( uniforms.shadowMatrix ) {
  2742. var j = 0;
  2743. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  2744. var light = lights[ i ];
  2745. if ( ! light.castShadow ) continue;
  2746. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  2747. uniforms.shadowMap.value[ j ] = light.shadowMap;
  2748. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  2749. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  2750. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  2751. uniforms.shadowBias.value[ j ] = light.shadowBias;
  2752. j ++;
  2753. }
  2754. }
  2755. }
  2756. };
  2757. // Uniforms (load to GPU)
  2758. function loadUniformsMatrices ( uniforms, object ) {
  2759. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  2760. if ( uniforms.normalMatrix ) {
  2761. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  2762. }
  2763. };
  2764. function getTextureUnit() {
  2765. var textureUnit = _usedTextureUnits;
  2766. if ( textureUnit >= _maxTextures ) {
  2767. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  2768. }
  2769. _usedTextureUnits += 1;
  2770. return textureUnit;
  2771. };
  2772. function loadUniformsGeneric ( program, uniforms ) {
  2773. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  2774. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  2775. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  2776. if ( ! location ) continue;
  2777. uniform = uniforms[ j ][ 0 ];
  2778. type = uniform.type;
  2779. value = uniform.value;
  2780. if ( type === 'i' ) { // single integer
  2781. _gl.uniform1i( location, value );
  2782. } else if ( type === 'f' ) { // single float
  2783. _gl.uniform1f( location, value );
  2784. } else if ( type === 'v2' ) { // single THREE.Vector2
  2785. _gl.uniform2f( location, value.x, value.y );
  2786. } else if ( type === 'v3' ) { // single THREE.Vector3
  2787. _gl.uniform3f( location, value.x, value.y, value.z );
  2788. } else if ( type === 'v4' ) { // single THREE.Vector4
  2789. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  2790. } else if ( type === 'c' ) { // single THREE.Color
  2791. _gl.uniform3f( location, value.r, value.g, value.b );
  2792. } else if ( type === 'iv1' ) { // flat array of integers (JS or typed array)
  2793. _gl.uniform1iv( location, value );
  2794. } else if ( type === 'iv' ) { // flat array of integers with 3 x N size (JS or typed array)
  2795. _gl.uniform3iv( location, value );
  2796. } else if ( type === 'fv1' ) { // flat array of floats (JS or typed array)
  2797. _gl.uniform1fv( location, value );
  2798. } else if ( type === 'fv' ) { // flat array of floats with 3 x N size (JS or typed array)
  2799. _gl.uniform3fv( location, value );
  2800. } else if ( type === 'v2v' ) { // array of THREE.Vector2
  2801. if ( uniform._array === undefined ) {
  2802. uniform._array = new Float32Array( 2 * value.length );
  2803. }
  2804. for ( i = 0, il = value.length; i < il; i ++ ) {
  2805. offset = i * 2;
  2806. uniform._array[ offset ] = value[ i ].x;
  2807. uniform._array[ offset + 1 ] = value[ i ].y;
  2808. }
  2809. _gl.uniform2fv( location, uniform._array );
  2810. } else if ( type === 'v3v' ) { // array of THREE.Vector3
  2811. if ( uniform._array === undefined ) {
  2812. uniform._array = new Float32Array( 3 * value.length );
  2813. }
  2814. for ( i = 0, il = value.length; i < il; i ++ ) {
  2815. offset = i * 3;
  2816. uniform._array[ offset ] = value[ i ].x;
  2817. uniform._array[ offset + 1 ] = value[ i ].y;
  2818. uniform._array[ offset + 2 ] = value[ i ].z;
  2819. }
  2820. _gl.uniform3fv( location, uniform._array );
  2821. } else if ( type === 'v4v' ) { // array of THREE.Vector4
  2822. if ( uniform._array === undefined ) {
  2823. uniform._array = new Float32Array( 4 * value.length );
  2824. }
  2825. for ( i = 0, il = value.length; i < il; i ++ ) {
  2826. offset = i * 4;
  2827. uniform._array[ offset ] = value[ i ].x;
  2828. uniform._array[ offset + 1 ] = value[ i ].y;
  2829. uniform._array[ offset + 2 ] = value[ i ].z;
  2830. uniform._array[ offset + 3 ] = value[ i ].w;
  2831. }
  2832. _gl.uniform4fv( location, uniform._array );
  2833. } else if ( type === 'm3' ) { // single THREE.Matrix3
  2834. _gl.uniformMatrix3fv( location, false, value.elements );
  2835. } else if ( type === 'm3v' ) { // array of THREE.Matrix3
  2836. if ( uniform._array === undefined ) {
  2837. uniform._array = new Float32Array( 9 * value.length );
  2838. }
  2839. for ( i = 0, il = value.length; i < il; i ++ ) {
  2840. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  2841. }
  2842. _gl.uniformMatrix3fv( location, false, uniform._array );
  2843. } else if ( type === 'm4' ) { // single THREE.Matrix4
  2844. _gl.uniformMatrix4fv( location, false, value.elements );
  2845. } else if ( type === 'm4v' ) { // array of THREE.Matrix4
  2846. if ( uniform._array === undefined ) {
  2847. uniform._array = new Float32Array( 16 * value.length );
  2848. }
  2849. for ( i = 0, il = value.length; i < il; i ++ ) {
  2850. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  2851. }
  2852. _gl.uniformMatrix4fv( location, false, uniform._array );
  2853. } else if ( type === 't' ) { // single THREE.Texture (2d or cube)
  2854. texture = value;
  2855. textureUnit = getTextureUnit();
  2856. _gl.uniform1i( location, textureUnit );
  2857. if ( ! texture ) continue;
  2858. if ( texture instanceof THREE.CubeTexture ||
  2859. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  2860. setCubeTexture( texture, textureUnit );
  2861. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  2862. setCubeTextureDynamic( texture, textureUnit );
  2863. } else {
  2864. _this.setTexture( texture, textureUnit );
  2865. }
  2866. } else if ( type === 'tv' ) { // array of THREE.Texture (2d)
  2867. if ( uniform._array === undefined ) {
  2868. uniform._array = [];
  2869. }
  2870. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2871. uniform._array[ i ] = getTextureUnit();
  2872. }
  2873. _gl.uniform1iv( location, uniform._array );
  2874. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2875. texture = uniform.value[ i ];
  2876. textureUnit = uniform._array[ i ];
  2877. if ( ! texture ) continue;
  2878. _this.setTexture( texture, textureUnit );
  2879. }
  2880. } else {
  2881. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  2882. }
  2883. }
  2884. };
  2885. function setupMatrices ( object, camera ) {
  2886. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  2887. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  2888. };
  2889. //
  2890. function setColorGamma( array, offset, color, intensitySq ) {
  2891. array[ offset ] = color.r * color.r * intensitySq;
  2892. array[ offset + 1 ] = color.g * color.g * intensitySq;
  2893. array[ offset + 2 ] = color.b * color.b * intensitySq;
  2894. };
  2895. function setColorLinear( array, offset, color, intensity ) {
  2896. array[ offset ] = color.r * intensity;
  2897. array[ offset + 1 ] = color.g * intensity;
  2898. array[ offset + 2 ] = color.b * intensity;
  2899. };
  2900. function setupLights ( program, lights ) {
  2901. var l, ll, light, n,
  2902. r = 0, g = 0, b = 0,
  2903. color, skyColor, groundColor,
  2904. intensity, intensitySq,
  2905. position,
  2906. distance,
  2907. zlights = _lights,
  2908. dirColors = zlights.directional.colors,
  2909. dirPositions = zlights.directional.positions,
  2910. pointColors = zlights.point.colors,
  2911. pointPositions = zlights.point.positions,
  2912. pointDistances = zlights.point.distances,
  2913. spotColors = zlights.spot.colors,
  2914. spotPositions = zlights.spot.positions,
  2915. spotDistances = zlights.spot.distances,
  2916. spotDirections = zlights.spot.directions,
  2917. spotAnglesCos = zlights.spot.anglesCos,
  2918. spotExponents = zlights.spot.exponents,
  2919. hemiSkyColors = zlights.hemi.skyColors,
  2920. hemiGroundColors = zlights.hemi.groundColors,
  2921. hemiPositions = zlights.hemi.positions,
  2922. dirLength = 0,
  2923. pointLength = 0,
  2924. spotLength = 0,
  2925. hemiLength = 0,
  2926. dirCount = 0,
  2927. pointCount = 0,
  2928. spotCount = 0,
  2929. hemiCount = 0,
  2930. dirOffset = 0,
  2931. pointOffset = 0,
  2932. spotOffset = 0,
  2933. hemiOffset = 0;
  2934. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  2935. light = lights[ l ];
  2936. if ( light.onlyShadow ) continue;
  2937. color = light.color;
  2938. intensity = light.intensity;
  2939. distance = light.distance;
  2940. if ( light instanceof THREE.AmbientLight ) {
  2941. if ( ! light.visible ) continue;
  2942. if ( _this.gammaInput ) {
  2943. r += color.r * color.r;
  2944. g += color.g * color.g;
  2945. b += color.b * color.b;
  2946. } else {
  2947. r += color.r;
  2948. g += color.g;
  2949. b += color.b;
  2950. }
  2951. } else if ( light instanceof THREE.DirectionalLight ) {
  2952. dirCount += 1;
  2953. if ( ! light.visible ) continue;
  2954. _direction.setFromMatrixPosition( light.matrixWorld );
  2955. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  2956. _direction.sub( _vector3 );
  2957. _direction.normalize();
  2958. // skip lights with undefined direction
  2959. // these create troubles in OpenGL (making pixel black)
  2960. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  2961. dirOffset = dirLength * 3;
  2962. dirPositions[ dirOffset ] = _direction.x;
  2963. dirPositions[ dirOffset + 1 ] = _direction.y;
  2964. dirPositions[ dirOffset + 2 ] = _direction.z;
  2965. if ( _this.gammaInput ) {
  2966. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  2967. } else {
  2968. setColorLinear( dirColors, dirOffset, color, intensity );
  2969. }
  2970. dirLength += 1;
  2971. } else if ( light instanceof THREE.PointLight ) {
  2972. pointCount += 1;
  2973. if ( ! light.visible ) continue;
  2974. pointOffset = pointLength * 3;
  2975. if ( _this.gammaInput ) {
  2976. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  2977. } else {
  2978. setColorLinear( pointColors, pointOffset, color, intensity );
  2979. }
  2980. _vector3.setFromMatrixPosition( light.matrixWorld );
  2981. pointPositions[ pointOffset ] = _vector3.x;
  2982. pointPositions[ pointOffset + 1 ] = _vector3.y;
  2983. pointPositions[ pointOffset + 2 ] = _vector3.z;
  2984. pointDistances[ pointLength ] = distance;
  2985. pointLength += 1;
  2986. } else if ( light instanceof THREE.SpotLight ) {
  2987. spotCount += 1;
  2988. if ( ! light.visible ) continue;
  2989. spotOffset = spotLength * 3;
  2990. if ( _this.gammaInput ) {
  2991. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  2992. } else {
  2993. setColorLinear( spotColors, spotOffset, color, intensity );
  2994. }
  2995. _vector3.setFromMatrixPosition( light.matrixWorld );
  2996. spotPositions[ spotOffset ] = _vector3.x;
  2997. spotPositions[ spotOffset + 1 ] = _vector3.y;
  2998. spotPositions[ spotOffset + 2 ] = _vector3.z;
  2999. spotDistances[ spotLength ] = distance;
  3000. _direction.copy( _vector3 );
  3001. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  3002. _direction.sub( _vector3 );
  3003. _direction.normalize();
  3004. spotDirections[ spotOffset ] = _direction.x;
  3005. spotDirections[ spotOffset + 1 ] = _direction.y;
  3006. spotDirections[ spotOffset + 2 ] = _direction.z;
  3007. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  3008. spotExponents[ spotLength ] = light.exponent;
  3009. spotLength += 1;
  3010. } else if ( light instanceof THREE.HemisphereLight ) {
  3011. hemiCount += 1;
  3012. if ( ! light.visible ) continue;
  3013. _direction.setFromMatrixPosition( light.matrixWorld );
  3014. _direction.normalize();
  3015. // skip lights with undefined direction
  3016. // these create troubles in OpenGL (making pixel black)
  3017. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  3018. hemiOffset = hemiLength * 3;
  3019. hemiPositions[ hemiOffset ] = _direction.x;
  3020. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  3021. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  3022. skyColor = light.color;
  3023. groundColor = light.groundColor;
  3024. if ( _this.gammaInput ) {
  3025. intensitySq = intensity * intensity;
  3026. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  3027. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  3028. } else {
  3029. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  3030. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  3031. }
  3032. hemiLength += 1;
  3033. }
  3034. }
  3035. // null eventual remains from removed lights
  3036. // (this is to avoid if in shader)
  3037. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  3038. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  3039. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  3040. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  3041. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  3042. zlights.directional.length = dirLength;
  3043. zlights.point.length = pointLength;
  3044. zlights.spot.length = spotLength;
  3045. zlights.hemi.length = hemiLength;
  3046. zlights.ambient[ 0 ] = r;
  3047. zlights.ambient[ 1 ] = g;
  3048. zlights.ambient[ 2 ] = b;
  3049. };
  3050. // GL state setting
  3051. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  3052. if ( cullFace === THREE.CullFaceNone ) {
  3053. _gl.disable( _gl.CULL_FACE );
  3054. } else {
  3055. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  3056. _gl.frontFace( _gl.CW );
  3057. } else {
  3058. _gl.frontFace( _gl.CCW );
  3059. }
  3060. if ( cullFace === THREE.CullFaceBack ) {
  3061. _gl.cullFace( _gl.BACK );
  3062. } else if ( cullFace === THREE.CullFaceFront ) {
  3063. _gl.cullFace( _gl.FRONT );
  3064. } else {
  3065. _gl.cullFace( _gl.FRONT_AND_BACK );
  3066. }
  3067. _gl.enable( _gl.CULL_FACE );
  3068. }
  3069. };
  3070. this.setMaterialFaces = function ( material ) {
  3071. var doubleSided = material.side === THREE.DoubleSide;
  3072. var flipSided = material.side === THREE.BackSide;
  3073. if ( _oldDoubleSided !== doubleSided ) {
  3074. if ( doubleSided ) {
  3075. _gl.disable( _gl.CULL_FACE );
  3076. } else {
  3077. _gl.enable( _gl.CULL_FACE );
  3078. }
  3079. _oldDoubleSided = doubleSided;
  3080. }
  3081. if ( _oldFlipSided !== flipSided ) {
  3082. if ( flipSided ) {
  3083. _gl.frontFace( _gl.CW );
  3084. } else {
  3085. _gl.frontFace( _gl.CCW );
  3086. }
  3087. _oldFlipSided = flipSided;
  3088. }
  3089. };
  3090. this.setDepthTest = function ( depthTest ) {
  3091. if ( _oldDepthTest !== depthTest ) {
  3092. if ( depthTest ) {
  3093. _gl.enable( _gl.DEPTH_TEST );
  3094. } else {
  3095. _gl.disable( _gl.DEPTH_TEST );
  3096. }
  3097. _oldDepthTest = depthTest;
  3098. }
  3099. };
  3100. this.setDepthWrite = function ( depthWrite ) {
  3101. if ( _oldDepthWrite !== depthWrite ) {
  3102. _gl.depthMask( depthWrite );
  3103. _oldDepthWrite = depthWrite;
  3104. }
  3105. };
  3106. function setLineWidth ( width ) {
  3107. if ( width !== _oldLineWidth ) {
  3108. _gl.lineWidth( width );
  3109. _oldLineWidth = width;
  3110. }
  3111. };
  3112. function setPolygonOffset ( polygonoffset, factor, units ) {
  3113. if ( _oldPolygonOffset !== polygonoffset ) {
  3114. if ( polygonoffset ) {
  3115. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  3116. } else {
  3117. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  3118. }
  3119. _oldPolygonOffset = polygonoffset;
  3120. }
  3121. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  3122. _gl.polygonOffset( factor, units );
  3123. _oldPolygonOffsetFactor = factor;
  3124. _oldPolygonOffsetUnits = units;
  3125. }
  3126. };
  3127. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  3128. if ( blending !== _oldBlending ) {
  3129. if ( blending === THREE.NoBlending ) {
  3130. _gl.disable( _gl.BLEND );
  3131. } else if ( blending === THREE.AdditiveBlending ) {
  3132. _gl.enable( _gl.BLEND );
  3133. _gl.blendEquation( _gl.FUNC_ADD );
  3134. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  3135. } else if ( blending === THREE.SubtractiveBlending ) {
  3136. // TODO: Find blendFuncSeparate() combination
  3137. _gl.enable( _gl.BLEND );
  3138. _gl.blendEquation( _gl.FUNC_ADD );
  3139. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  3140. } else if ( blending === THREE.MultiplyBlending ) {
  3141. // TODO: Find blendFuncSeparate() combination
  3142. _gl.enable( _gl.BLEND );
  3143. _gl.blendEquation( _gl.FUNC_ADD );
  3144. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  3145. } else if ( blending === THREE.CustomBlending ) {
  3146. _gl.enable( _gl.BLEND );
  3147. } else {
  3148. _gl.enable( _gl.BLEND );
  3149. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  3150. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  3151. }
  3152. _oldBlending = blending;
  3153. }
  3154. if ( blending === THREE.CustomBlending ) {
  3155. if ( blendEquation !== _oldBlendEquation ) {
  3156. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  3157. _oldBlendEquation = blendEquation;
  3158. }
  3159. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  3160. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  3161. _oldBlendSrc = blendSrc;
  3162. _oldBlendDst = blendDst;
  3163. }
  3164. } else {
  3165. _oldBlendEquation = null;
  3166. _oldBlendSrc = null;
  3167. _oldBlendDst = null;
  3168. }
  3169. };
  3170. // Textures
  3171. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  3172. if ( isImagePowerOfTwo ) {
  3173. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3174. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3175. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3176. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3177. } else {
  3178. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3179. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3180. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3181. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3182. }
  3183. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  3184. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  3185. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  3186. texture.__oldAnisotropy = texture.anisotropy;
  3187. }
  3188. }
  3189. };
  3190. this.setTexture = function ( texture, slot ) {
  3191. if ( texture.needsUpdate ) {
  3192. if ( ! texture.__webglInit ) {
  3193. texture.__webglInit = true;
  3194. texture.addEventListener( 'dispose', onTextureDispose );
  3195. texture.__webglTexture = _gl.createTexture();
  3196. _this.info.memory.textures ++;
  3197. }
  3198. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3199. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3200. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3201. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3202. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3203. var image = texture.image,
  3204. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3205. glFormat = paramThreeToGL( texture.format ),
  3206. glType = paramThreeToGL( texture.type );
  3207. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  3208. var mipmap, mipmaps = texture.mipmaps;
  3209. if ( texture instanceof THREE.DataTexture ) {
  3210. // use manually created mipmaps if available
  3211. // if there are no manual mipmaps
  3212. // set 0 level mipmap and then use GL to generate other mipmap levels
  3213. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3214. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3215. mipmap = mipmaps[ i ];
  3216. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3217. }
  3218. texture.generateMipmaps = false;
  3219. } else {
  3220. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3221. }
  3222. } else if ( texture instanceof THREE.CompressedTexture ) {
  3223. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3224. mipmap = mipmaps[ i ];
  3225. if ( texture.format !== THREE.RGBAFormat ) {
  3226. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3227. } else {
  3228. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3229. }
  3230. }
  3231. } else { // regular Texture (image, video, canvas)
  3232. // use manually created mipmaps if available
  3233. // if there are no manual mipmaps
  3234. // set 0 level mipmap and then use GL to generate other mipmap levels
  3235. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3236. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3237. mipmap = mipmaps[ i ];
  3238. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3239. }
  3240. texture.generateMipmaps = false;
  3241. } else {
  3242. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  3243. }
  3244. }
  3245. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3246. texture.needsUpdate = false;
  3247. if ( texture.onUpdate ) texture.onUpdate();
  3248. } else {
  3249. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3250. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3251. }
  3252. };
  3253. function clampToMaxSize ( image, maxSize ) {
  3254. if ( image.width <= maxSize && image.height <= maxSize ) {
  3255. return image;
  3256. }
  3257. // Warning: Scaling through the canvas will only work with images that use
  3258. // premultiplied alpha.
  3259. var maxDimension = Math.max( image.width, image.height );
  3260. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  3261. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  3262. var canvas = document.createElement( 'canvas' );
  3263. canvas.width = newWidth;
  3264. canvas.height = newHeight;
  3265. var ctx = canvas.getContext( '2d' );
  3266. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  3267. return canvas;
  3268. }
  3269. function setCubeTexture ( texture, slot ) {
  3270. if ( texture.image.length === 6 ) {
  3271. if ( texture.needsUpdate ) {
  3272. if ( ! texture.image.__webglTextureCube ) {
  3273. texture.addEventListener( 'dispose', onTextureDispose );
  3274. texture.image.__webglTextureCube = _gl.createTexture();
  3275. _this.info.memory.textures ++;
  3276. }
  3277. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3278. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3279. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3280. var isCompressed = texture instanceof THREE.CompressedTexture;
  3281. var cubeImage = [];
  3282. for ( var i = 0; i < 6; i ++ ) {
  3283. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  3284. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  3285. } else {
  3286. cubeImage[ i ] = texture.image[ i ];
  3287. }
  3288. }
  3289. var image = cubeImage[ 0 ],
  3290. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3291. glFormat = paramThreeToGL( texture.format ),
  3292. glType = paramThreeToGL( texture.type );
  3293. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  3294. for ( var i = 0; i < 6; i ++ ) {
  3295. if ( ! isCompressed ) {
  3296. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3297. } else {
  3298. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3299. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3300. mipmap = mipmaps[ j ];
  3301. if ( texture.format !== THREE.RGBAFormat ) {
  3302. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3303. } else {
  3304. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3305. }
  3306. }
  3307. }
  3308. }
  3309. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  3310. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3311. }
  3312. texture.needsUpdate = false;
  3313. if ( texture.onUpdate ) texture.onUpdate();
  3314. } else {
  3315. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3316. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3317. }
  3318. }
  3319. };
  3320. function setCubeTextureDynamic ( texture, slot ) {
  3321. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3322. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  3323. };
  3324. // Render targets
  3325. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  3326. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3327. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  3328. };
  3329. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  3330. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3331. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3332. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3333. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3334. /* For some reason this is not working. Defaulting to RGBA4.
  3335. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3336. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  3337. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3338. */
  3339. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3340. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3341. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3342. } else {
  3343. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3344. }
  3345. };
  3346. this.setRenderTarget = function ( renderTarget ) {
  3347. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  3348. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  3349. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  3350. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  3351. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3352. renderTarget.__webglTexture = _gl.createTexture();
  3353. _this.info.memory.textures ++;
  3354. // Setup texture, create render and frame buffers
  3355. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  3356. glFormat = paramThreeToGL( renderTarget.format ),
  3357. glType = paramThreeToGL( renderTarget.type );
  3358. if ( isCube ) {
  3359. renderTarget.__webglFramebuffer = [];
  3360. renderTarget.__webglRenderbuffer = [];
  3361. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3362. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  3363. for ( var i = 0; i < 6; i ++ ) {
  3364. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3365. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  3366. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3367. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3368. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  3369. }
  3370. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3371. } else {
  3372. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  3373. if ( renderTarget.shareDepthFrom ) {
  3374. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  3375. } else {
  3376. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  3377. }
  3378. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3379. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  3380. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3381. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  3382. if ( renderTarget.shareDepthFrom ) {
  3383. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3384. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3385. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3386. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3387. }
  3388. } else {
  3389. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  3390. }
  3391. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3392. }
  3393. // Release everything
  3394. if ( isCube ) {
  3395. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3396. } else {
  3397. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3398. }
  3399. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3400. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3401. }
  3402. var framebuffer, width, height, vx, vy;
  3403. if ( renderTarget ) {
  3404. if ( isCube ) {
  3405. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  3406. } else {
  3407. framebuffer = renderTarget.__webglFramebuffer;
  3408. }
  3409. width = renderTarget.width;
  3410. height = renderTarget.height;
  3411. vx = 0;
  3412. vy = 0;
  3413. } else {
  3414. framebuffer = null;
  3415. width = _viewportWidth;
  3416. height = _viewportHeight;
  3417. vx = _viewportX;
  3418. vy = _viewportY;
  3419. }
  3420. if ( framebuffer !== _currentFramebuffer ) {
  3421. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3422. _gl.viewport( vx, vy, width, height );
  3423. _currentFramebuffer = framebuffer;
  3424. }
  3425. _currentWidth = width;
  3426. _currentHeight = height;
  3427. };
  3428. function updateRenderTargetMipmap ( renderTarget ) {
  3429. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  3430. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3431. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3432. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3433. } else {
  3434. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3435. _gl.generateMipmap( _gl.TEXTURE_2D );
  3436. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3437. }
  3438. };
  3439. // Fallback filters for non-power-of-2 textures
  3440. function filterFallback ( f ) {
  3441. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  3442. return _gl.NEAREST;
  3443. }
  3444. return _gl.LINEAR;
  3445. };
  3446. // Map three.js constants to WebGL constants
  3447. function paramThreeToGL ( p ) {
  3448. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  3449. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  3450. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  3451. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  3452. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  3453. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  3454. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  3455. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  3456. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  3457. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  3458. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  3459. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  3460. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  3461. if ( p === THREE.ByteType ) return _gl.BYTE;
  3462. if ( p === THREE.ShortType ) return _gl.SHORT;
  3463. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  3464. if ( p === THREE.IntType ) return _gl.INT;
  3465. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  3466. if ( p === THREE.FloatType ) return _gl.FLOAT;
  3467. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  3468. if ( p === THREE.RGBFormat ) return _gl.RGB;
  3469. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  3470. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  3471. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  3472. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  3473. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  3474. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  3475. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  3476. if ( p === THREE.OneFactor ) return _gl.ONE;
  3477. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  3478. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  3479. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  3480. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  3481. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  3482. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  3483. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  3484. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  3485. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  3486. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  3487. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  3488. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3489. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3490. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3491. }
  3492. return 0;
  3493. };
  3494. // Allocations
  3495. function allocateBones ( object ) {
  3496. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  3497. return 1024;
  3498. } else {
  3499. // default for when object is not specified
  3500. // ( for example when prebuilding shader
  3501. // to be used with multiple objects )
  3502. //
  3503. // - leave some extra space for other uniforms
  3504. // - limit here is ANGLE's 254 max uniform vectors
  3505. // (up to 54 should be safe)
  3506. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  3507. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  3508. var maxBones = nVertexMatrices;
  3509. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  3510. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  3511. if ( maxBones < object.skeleton.bones.length ) {
  3512. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  3513. }
  3514. }
  3515. return maxBones;
  3516. }
  3517. };
  3518. function allocateLights( lights ) {
  3519. var dirLights = 0;
  3520. var pointLights = 0;
  3521. var spotLights = 0;
  3522. var hemiLights = 0;
  3523. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3524. var light = lights[ l ];
  3525. if ( light.onlyShadow || light.visible === false ) continue;
  3526. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  3527. if ( light instanceof THREE.PointLight ) pointLights ++;
  3528. if ( light instanceof THREE.SpotLight ) spotLights ++;
  3529. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  3530. }
  3531. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  3532. };
  3533. function allocateShadows( lights ) {
  3534. var maxShadows = 0;
  3535. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3536. var light = lights[ l ];
  3537. if ( ! light.castShadow ) continue;
  3538. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  3539. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  3540. }
  3541. return maxShadows;
  3542. };
  3543. // Initialization
  3544. function initGL() {
  3545. try {
  3546. var attributes = {
  3547. alpha: _alpha,
  3548. depth: _depth,
  3549. stencil: _stencil,
  3550. antialias: _antialias,
  3551. premultipliedAlpha: _premultipliedAlpha,
  3552. preserveDrawingBuffer: _preserveDrawingBuffer
  3553. };
  3554. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  3555. if ( _gl === null ) {
  3556. throw 'Error creating WebGL context.';
  3557. }
  3558. } catch ( error ) {
  3559. console.error( error );
  3560. }
  3561. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  3562. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  3563. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  3564. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  3565. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  3566. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  3567. if ( _glExtensionTextureFloat === null ) {
  3568. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  3569. }
  3570. if ( _glExtensionStandardDerivatives === null ) {
  3571. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  3572. }
  3573. if ( _glExtensionTextureFilterAnisotropic === null ) {
  3574. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  3575. }
  3576. if ( _glExtensionCompressedTextureS3TC === null ) {
  3577. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  3578. }
  3579. if ( _glExtensionElementIndexUint === null ) {
  3580. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  3581. }
  3582. if ( _gl.getShaderPrecisionFormat === undefined ) {
  3583. _gl.getShaderPrecisionFormat = function () {
  3584. return {
  3585. 'rangeMin': 1,
  3586. 'rangeMax': 1,
  3587. 'precision': 1
  3588. };
  3589. }
  3590. }
  3591. if ( _logarithmicDepthBuffer ) {
  3592. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  3593. }
  3594. };
  3595. function setDefaultGLState () {
  3596. _gl.clearColor( 0, 0, 0, 1 );
  3597. _gl.clearDepth( 1 );
  3598. _gl.clearStencil( 0 );
  3599. _gl.enable( _gl.DEPTH_TEST );
  3600. _gl.depthFunc( _gl.LEQUAL );
  3601. _gl.frontFace( _gl.CCW );
  3602. _gl.cullFace( _gl.BACK );
  3603. _gl.enable( _gl.CULL_FACE );
  3604. _gl.enable( _gl.BLEND );
  3605. _gl.blendEquation( _gl.FUNC_ADD );
  3606. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  3607. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  3608. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  3609. };
  3610. // default plugins (order is important)
  3611. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  3612. this.addPrePlugin( this.shadowMapPlugin );
  3613. this.addPostPlugin( new THREE.SpritePlugin() );
  3614. this.addPostPlugin( new THREE.LensFlarePlugin() );
  3615. };