WebGLRenderer.js 144 KB

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