WebGLRenderer.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653
  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. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  17. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  18. var lights = [];
  19. var opaqueObjects = [];
  20. var opaqueObjectsLastIndex = - 1;
  21. var transparentObjects = [];
  22. var transparentObjectsLastIndex = - 1;
  23. var morphInfluences = new Float32Array( 8 );
  24. var sprites = [];
  25. var lensFlares = [];
  26. // public properties
  27. this.domElement = _canvas;
  28. this.context = null;
  29. // clearing
  30. this.autoClear = true;
  31. this.autoClearColor = true;
  32. this.autoClearDepth = true;
  33. this.autoClearStencil = true;
  34. // scene graph
  35. this.sortObjects = true;
  36. // physically based shading
  37. this.gammaFactor = 2.0; // for backwards compatibility
  38. this.gammaInput = false;
  39. this.gammaOutput = false;
  40. // tone mapping
  41. this.toneMapping = THREE.LinearToneMapping;
  42. this.toneMappingExposure = 1.0;
  43. this.toneMappingWhitePoint = 1.0;
  44. // morphs
  45. this.maxMorphTargets = 8;
  46. this.maxMorphNormals = 4;
  47. // flags
  48. this.autoScaleCubemaps = true;
  49. // internal properties
  50. var _this = this,
  51. // internal state cache
  52. _currentProgram = null,
  53. _currentRenderTarget = null,
  54. _currentFramebuffer = null,
  55. _currentMaterialId = - 1,
  56. _currentGeometryProgram = '',
  57. _currentCamera = null,
  58. _currentScissor = new THREE.Vector4(),
  59. _currentScissorTest = null,
  60. _currentViewport = new THREE.Vector4(),
  61. //
  62. _usedTextureUnits = 0,
  63. //
  64. _clearColor = new THREE.Color( 0x000000 ),
  65. _clearAlpha = 0,
  66. _width = _canvas.width,
  67. _height = _canvas.height,
  68. _pixelRatio = 1,
  69. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  70. _scissorTest = false,
  71. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  72. // frustum
  73. _frustum = new THREE.Frustum(),
  74. // camera matrices cache
  75. _projScreenMatrix = new THREE.Matrix4(),
  76. _vector3 = new THREE.Vector3(),
  77. // light arrays cache
  78. _lights = {
  79. hash: '',
  80. ambient: [ 0, 0, 0 ],
  81. directional: [],
  82. directionalShadowMap: [],
  83. directionalShadowMatrix: [],
  84. spot: [],
  85. spotShadowMap: [],
  86. spotShadowMatrix: [],
  87. point: [],
  88. pointShadowMap: [],
  89. pointShadowMatrix: [],
  90. hemi: [],
  91. shadows: [],
  92. shadowsPointLight: 0
  93. },
  94. // info
  95. _infoMemory = {
  96. geometries: 0,
  97. textures: 0
  98. },
  99. _infoRender = {
  100. calls: 0,
  101. vertices: 0,
  102. faces: 0,
  103. points: 0
  104. };
  105. this.info = {
  106. render: _infoRender,
  107. memory: _infoMemory,
  108. programs: null
  109. };
  110. // initialize
  111. var _gl;
  112. try {
  113. var attributes = {
  114. alpha: _alpha,
  115. depth: _depth,
  116. stencil: _stencil,
  117. antialias: _antialias,
  118. premultipliedAlpha: _premultipliedAlpha,
  119. preserveDrawingBuffer: _preserveDrawingBuffer
  120. };
  121. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  122. if ( _gl === null ) {
  123. if ( _canvas.getContext( 'webgl' ) !== null ) {
  124. throw 'Error creating WebGL context with your selected attributes.';
  125. } else {
  126. throw 'Error creating WebGL context.';
  127. }
  128. }
  129. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  130. } catch ( error ) {
  131. console.error( 'THREE.WebGLRenderer: ' + error );
  132. }
  133. var extensions = new THREE.WebGLExtensions( _gl );
  134. extensions.get( 'OES_texture_float' );
  135. extensions.get( 'OES_texture_float_linear' );
  136. extensions.get( 'OES_texture_half_float' );
  137. extensions.get( 'OES_texture_half_float_linear' );
  138. extensions.get( 'OES_standard_derivatives' );
  139. extensions.get( 'ANGLE_instanced_arrays' );
  140. if ( extensions.get( 'OES_element_index_uint' ) ) {
  141. THREE.BufferGeometry.MaxIndex = 4294967296;
  142. }
  143. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  144. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  145. var properties = new THREE.WebGLProperties();
  146. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  147. var programCache = new THREE.WebGLPrograms( this, capabilities );
  148. var lightCache = new THREE.WebGLLights();
  149. this.info.programs = programCache.programs;
  150. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  151. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  152. //
  153. function getTargetPixelRatio() {
  154. return _currentRenderTarget === null ? _pixelRatio : 1;
  155. }
  156. function glClearColor( r, g, b, a ) {
  157. if ( _premultipliedAlpha === true ) {
  158. r *= a; g *= a; b *= a;
  159. }
  160. state.clearColor( r, g, b, a );
  161. }
  162. function setDefaultGLState() {
  163. state.init();
  164. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  165. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  166. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  167. }
  168. function resetGLState() {
  169. _currentProgram = null;
  170. _currentCamera = null;
  171. _currentGeometryProgram = '';
  172. _currentMaterialId = - 1;
  173. state.reset();
  174. }
  175. setDefaultGLState();
  176. this.context = _gl;
  177. this.capabilities = capabilities;
  178. this.extensions = extensions;
  179. this.properties = properties;
  180. this.state = state;
  181. // shadow map
  182. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  183. this.shadowMap = shadowMap;
  184. // Plugins
  185. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  186. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  187. // API
  188. this.getContext = function () {
  189. return _gl;
  190. };
  191. this.getContextAttributes = function () {
  192. return _gl.getContextAttributes();
  193. };
  194. this.forceContextLoss = function () {
  195. extensions.get( 'WEBGL_lose_context' ).loseContext();
  196. };
  197. this.getMaxAnisotropy = ( function () {
  198. var value;
  199. return function getMaxAnisotropy() {
  200. if ( value !== undefined ) return value;
  201. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  202. if ( extension !== null ) {
  203. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  204. } else {
  205. value = 0;
  206. }
  207. return value;
  208. };
  209. } )();
  210. this.getPrecision = function () {
  211. return capabilities.precision;
  212. };
  213. this.getPixelRatio = function () {
  214. return _pixelRatio;
  215. };
  216. this.setPixelRatio = function ( value ) {
  217. if ( value === undefined ) return;
  218. _pixelRatio = value;
  219. this.setSize( _viewport.z, _viewport.w, false );
  220. };
  221. this.getSize = function () {
  222. return {
  223. width: _width,
  224. height: _height
  225. };
  226. };
  227. this.setSize = function ( width, height, updateStyle ) {
  228. _width = width;
  229. _height = height;
  230. _canvas.width = width * _pixelRatio;
  231. _canvas.height = height * _pixelRatio;
  232. if ( updateStyle !== false ) {
  233. _canvas.style.width = width + 'px';
  234. _canvas.style.height = height + 'px';
  235. }
  236. this.setViewport( 0, 0, width, height );
  237. };
  238. this.setViewport = function ( x, y, width, height ) {
  239. state.viewport( _viewport.set( x, y, width, height ) );
  240. };
  241. this.setScissor = function ( x, y, width, height ) {
  242. state.scissor( _scissor.set( x, y, width, height ) );
  243. };
  244. this.setScissorTest = function ( boolean ) {
  245. state.setScissorTest( _scissorTest = boolean );
  246. };
  247. // Clearing
  248. this.getClearColor = function () {
  249. return _clearColor;
  250. };
  251. this.setClearColor = function ( color, alpha ) {
  252. _clearColor.set( color );
  253. _clearAlpha = alpha !== undefined ? alpha : 1;
  254. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  255. };
  256. this.getClearAlpha = function () {
  257. return _clearAlpha;
  258. };
  259. this.setClearAlpha = function ( alpha ) {
  260. _clearAlpha = alpha;
  261. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  262. };
  263. this.clear = function ( color, depth, stencil ) {
  264. var bits = 0;
  265. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  266. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  267. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  268. _gl.clear( bits );
  269. };
  270. this.clearColor = function () {
  271. this.clear( true, false, false );
  272. };
  273. this.clearDepth = function () {
  274. this.clear( false, true, false );
  275. };
  276. this.clearStencil = function () {
  277. this.clear( false, false, true );
  278. };
  279. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  280. this.setRenderTarget( renderTarget );
  281. this.clear( color, depth, stencil );
  282. };
  283. // Reset
  284. this.resetGLState = resetGLState;
  285. this.dispose = function() {
  286. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  287. };
  288. // Events
  289. function onContextLost( event ) {
  290. event.preventDefault();
  291. resetGLState();
  292. setDefaultGLState();
  293. properties.clear();
  294. }
  295. function onTextureDispose( event ) {
  296. var texture = event.target;
  297. texture.removeEventListener( 'dispose', onTextureDispose );
  298. deallocateTexture( texture );
  299. _infoMemory.textures --;
  300. }
  301. function onRenderTargetDispose( event ) {
  302. var renderTarget = event.target;
  303. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  304. deallocateRenderTarget( renderTarget );
  305. _infoMemory.textures --;
  306. }
  307. function onMaterialDispose( event ) {
  308. var material = event.target;
  309. material.removeEventListener( 'dispose', onMaterialDispose );
  310. deallocateMaterial( material );
  311. }
  312. // Buffer deallocation
  313. function deallocateTexture( texture ) {
  314. var textureProperties = properties.get( texture );
  315. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  316. // cube texture
  317. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  318. } else {
  319. // 2D texture
  320. if ( textureProperties.__webglInit === undefined ) return;
  321. _gl.deleteTexture( textureProperties.__webglTexture );
  322. }
  323. // remove all webgl properties
  324. properties.delete( texture );
  325. }
  326. function deallocateRenderTarget( renderTarget ) {
  327. var renderTargetProperties = properties.get( renderTarget );
  328. var textureProperties = properties.get( renderTarget.texture );
  329. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  330. _gl.deleteTexture( textureProperties.__webglTexture );
  331. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  332. for ( var i = 0; i < 6; i ++ ) {
  333. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  334. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  335. }
  336. } else {
  337. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  338. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  339. }
  340. properties.delete( renderTarget.texture );
  341. properties.delete( renderTarget );
  342. }
  343. function deallocateMaterial( material ) {
  344. releaseMaterialProgramReference( material );
  345. properties.delete( material );
  346. }
  347. function releaseMaterialProgramReference( material ) {
  348. var programInfo = properties.get( material ).program;
  349. material.program = undefined;
  350. if ( programInfo !== undefined ) {
  351. programCache.releaseProgram( programInfo );
  352. }
  353. }
  354. // Buffer rendering
  355. this.renderBufferImmediate = function ( object, program, material ) {
  356. state.initAttributes();
  357. var buffers = properties.get( object );
  358. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  359. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  360. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  361. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  362. var attributes = program.getAttributes();
  363. if ( object.hasPositions ) {
  364. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  365. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  366. state.enableAttribute( attributes.position );
  367. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  368. }
  369. if ( object.hasNormals ) {
  370. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  371. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  372. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  373. var array = object.normalArray;
  374. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  375. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  376. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  377. array[ i + 0 ] = nx;
  378. array[ i + 1 ] = ny;
  379. array[ i + 2 ] = nz;
  380. array[ i + 3 ] = nx;
  381. array[ i + 4 ] = ny;
  382. array[ i + 5 ] = nz;
  383. array[ i + 6 ] = nx;
  384. array[ i + 7 ] = ny;
  385. array[ i + 8 ] = nz;
  386. }
  387. }
  388. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  389. state.enableAttribute( attributes.normal );
  390. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  391. }
  392. if ( object.hasUvs && material.map ) {
  393. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  394. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  395. state.enableAttribute( attributes.uv );
  396. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  397. }
  398. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  399. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  400. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  401. state.enableAttribute( attributes.color );
  402. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  403. }
  404. state.disableUnusedAttributes();
  405. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  406. object.count = 0;
  407. };
  408. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  409. setMaterial( material );
  410. var program = setProgram( camera, fog, material, object );
  411. var updateBuffers = false;
  412. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  413. if ( geometryProgram !== _currentGeometryProgram ) {
  414. _currentGeometryProgram = geometryProgram;
  415. updateBuffers = true;
  416. }
  417. // morph targets
  418. var morphTargetInfluences = object.morphTargetInfluences;
  419. if ( morphTargetInfluences !== undefined ) {
  420. var activeInfluences = [];
  421. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  422. var influence = morphTargetInfluences[ i ];
  423. activeInfluences.push( [ influence, i ] );
  424. }
  425. activeInfluences.sort( absNumericalSort );
  426. if ( activeInfluences.length > 8 ) {
  427. activeInfluences.length = 8;
  428. }
  429. var morphAttributes = geometry.morphAttributes;
  430. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  431. var influence = activeInfluences[ i ];
  432. morphInfluences[ i ] = influence[ 0 ];
  433. if ( influence[ 0 ] !== 0 ) {
  434. var index = influence[ 1 ];
  435. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  436. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  437. } else {
  438. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  439. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  440. }
  441. }
  442. var uniforms = program.getUniforms();
  443. if ( uniforms.morphTargetInfluences !== null ) {
  444. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  445. }
  446. updateBuffers = true;
  447. }
  448. //
  449. var index = geometry.index;
  450. var position = geometry.attributes.position;
  451. if ( material.wireframe === true ) {
  452. index = objects.getWireframeAttribute( geometry );
  453. }
  454. var renderer;
  455. if ( index !== null ) {
  456. renderer = indexedBufferRenderer;
  457. renderer.setIndex( index );
  458. } else {
  459. renderer = bufferRenderer;
  460. }
  461. if ( updateBuffers ) {
  462. setupVertexAttributes( material, program, geometry );
  463. if ( index !== null ) {
  464. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  465. }
  466. }
  467. //
  468. var dataStart = 0;
  469. var dataCount = Infinity;
  470. if ( index !== null ) {
  471. dataCount = index.count;
  472. } else if ( position !== undefined ) {
  473. dataCount = position.count;
  474. }
  475. var rangeStart = geometry.drawRange.start;
  476. var rangeCount = geometry.drawRange.count;
  477. var groupStart = group !== null ? group.start : 0;
  478. var groupCount = group !== null ? group.count : Infinity;
  479. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  480. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  481. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  482. //
  483. if ( object instanceof THREE.Mesh ) {
  484. if ( material.wireframe === true ) {
  485. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  486. renderer.setMode( _gl.LINES );
  487. } else {
  488. switch ( object.drawMode ) {
  489. case THREE.TrianglesDrawMode:
  490. renderer.setMode( _gl.TRIANGLES );
  491. break;
  492. case THREE.TriangleStripDrawMode:
  493. renderer.setMode( _gl.TRIANGLE_STRIP );
  494. break;
  495. case THREE.TriangleFanDrawMode:
  496. renderer.setMode( _gl.TRIANGLE_FAN );
  497. break;
  498. }
  499. }
  500. } else if ( object instanceof THREE.Line ) {
  501. var lineWidth = material.linewidth;
  502. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  503. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  504. if ( object instanceof THREE.LineSegments ) {
  505. renderer.setMode( _gl.LINES );
  506. } else {
  507. renderer.setMode( _gl.LINE_STRIP );
  508. }
  509. } else if ( object instanceof THREE.Points ) {
  510. renderer.setMode( _gl.POINTS );
  511. }
  512. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  513. renderer.renderInstances( geometry, drawStart, drawCount );
  514. } else {
  515. renderer.render( drawStart, drawCount );
  516. }
  517. };
  518. function setupVertexAttributes( material, program, geometry, startIndex ) {
  519. var extension;
  520. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  521. extension = extensions.get( 'ANGLE_instanced_arrays' );
  522. if ( extension === null ) {
  523. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  524. return;
  525. }
  526. }
  527. if ( startIndex === undefined ) startIndex = 0;
  528. state.initAttributes();
  529. var geometryAttributes = geometry.attributes;
  530. var programAttributes = program.getAttributes();
  531. var materialDefaultAttributeValues = material.defaultAttributeValues;
  532. for ( var name in programAttributes ) {
  533. var programAttribute = programAttributes[ name ];
  534. if ( programAttribute >= 0 ) {
  535. var geometryAttribute = geometryAttributes[ name ];
  536. if ( geometryAttribute !== undefined ) {
  537. var size = geometryAttribute.itemSize;
  538. var buffer = objects.getAttributeBuffer( geometryAttribute );
  539. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  540. var data = geometryAttribute.data;
  541. var stride = data.stride;
  542. var offset = geometryAttribute.offset;
  543. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  544. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  545. if ( geometry.maxInstancedCount === undefined ) {
  546. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  547. }
  548. } else {
  549. state.enableAttribute( programAttribute );
  550. }
  551. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  552. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  553. } else {
  554. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  555. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  556. if ( geometry.maxInstancedCount === undefined ) {
  557. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  558. }
  559. } else {
  560. state.enableAttribute( programAttribute );
  561. }
  562. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  563. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  564. }
  565. } else if ( materialDefaultAttributeValues !== undefined ) {
  566. var value = materialDefaultAttributeValues[ name ];
  567. if ( value !== undefined ) {
  568. switch ( value.length ) {
  569. case 2:
  570. _gl.vertexAttrib2fv( programAttribute, value );
  571. break;
  572. case 3:
  573. _gl.vertexAttrib3fv( programAttribute, value );
  574. break;
  575. case 4:
  576. _gl.vertexAttrib4fv( programAttribute, value );
  577. break;
  578. default:
  579. _gl.vertexAttrib1fv( programAttribute, value );
  580. }
  581. }
  582. }
  583. }
  584. }
  585. state.disableUnusedAttributes();
  586. }
  587. // Sorting
  588. function absNumericalSort( a, b ) {
  589. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  590. }
  591. function painterSortStable ( a, b ) {
  592. if ( a.object.renderOrder !== b.object.renderOrder ) {
  593. return a.object.renderOrder - b.object.renderOrder;
  594. } else if ( a.material.id !== b.material.id ) {
  595. return a.material.id - b.material.id;
  596. } else if ( a.z !== b.z ) {
  597. return a.z - b.z;
  598. } else {
  599. return a.id - b.id;
  600. }
  601. }
  602. function reversePainterSortStable ( a, b ) {
  603. if ( a.object.renderOrder !== b.object.renderOrder ) {
  604. return a.object.renderOrder - b.object.renderOrder;
  605. } if ( a.z !== b.z ) {
  606. return b.z - a.z;
  607. } else {
  608. return a.id - b.id;
  609. }
  610. }
  611. // Rendering
  612. this.render = function ( scene, camera, renderTarget, forceClear ) {
  613. if ( camera instanceof THREE.Camera === false ) {
  614. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  615. return;
  616. }
  617. var fog = scene.fog;
  618. // reset caching for this frame
  619. _currentGeometryProgram = '';
  620. _currentMaterialId = - 1;
  621. _currentCamera = null;
  622. // update scene graph
  623. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  624. // update camera matrices and frustum
  625. if ( camera.parent === null ) camera.updateMatrixWorld();
  626. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  627. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  628. _frustum.setFromMatrix( _projScreenMatrix );
  629. lights.length = 0;
  630. opaqueObjectsLastIndex = - 1;
  631. transparentObjectsLastIndex = - 1;
  632. sprites.length = 0;
  633. lensFlares.length = 0;
  634. projectObject( scene, camera );
  635. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  636. transparentObjects.length = transparentObjectsLastIndex + 1;
  637. if ( _this.sortObjects === true ) {
  638. opaqueObjects.sort( painterSortStable );
  639. transparentObjects.sort( reversePainterSortStable );
  640. }
  641. setupLights( lights, camera );
  642. //
  643. shadowMap.render( scene, camera );
  644. //
  645. _infoRender.calls = 0;
  646. _infoRender.vertices = 0;
  647. _infoRender.faces = 0;
  648. _infoRender.points = 0;
  649. if ( renderTarget === undefined ) {
  650. renderTarget = null;
  651. }
  652. this.setRenderTarget( renderTarget );
  653. if ( this.autoClear || forceClear ) {
  654. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  655. }
  656. //
  657. if ( scene.overrideMaterial ) {
  658. var overrideMaterial = scene.overrideMaterial;
  659. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  660. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  661. } else {
  662. // opaque pass (front-to-back order)
  663. state.setBlending( THREE.NoBlending );
  664. renderObjects( opaqueObjects, camera, fog );
  665. // transparent pass (back-to-front order)
  666. renderObjects( transparentObjects, camera, fog );
  667. }
  668. // custom render plugins (post pass)
  669. spritePlugin.render( scene, camera );
  670. lensFlarePlugin.render( scene, camera, _currentViewport );
  671. // Generate mipmap if we're using any kind of mipmap filtering
  672. if ( renderTarget ) {
  673. var texture = renderTarget.texture;
  674. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  675. texture.minFilter !== THREE.NearestFilter &&
  676. texture.minFilter !== THREE.LinearFilter ) {
  677. updateRenderTargetMipmap( renderTarget );
  678. }
  679. }
  680. // Ensure depth buffer writing is enabled so it can be cleared on next render
  681. state.setDepthTest( true );
  682. state.setDepthWrite( true );
  683. state.setColorWrite( true );
  684. // _gl.finish();
  685. };
  686. function pushRenderItem( object, geometry, material, z, group ) {
  687. var array, index;
  688. // allocate the next position in the appropriate array
  689. if ( material.transparent ) {
  690. array = transparentObjects;
  691. index = ++ transparentObjectsLastIndex;
  692. } else {
  693. array = opaqueObjects;
  694. index = ++ opaqueObjectsLastIndex;
  695. }
  696. // recycle existing render item or grow the array
  697. var renderItem = array[ index ];
  698. if ( renderItem !== undefined ) {
  699. renderItem.id = object.id;
  700. renderItem.object = object;
  701. renderItem.geometry = geometry;
  702. renderItem.material = material;
  703. renderItem.z = _vector3.z;
  704. renderItem.group = group;
  705. } else {
  706. renderItem = {
  707. id: object.id,
  708. object: object,
  709. geometry: geometry,
  710. material: material,
  711. z: _vector3.z,
  712. group: group
  713. };
  714. // assert( index === array.length );
  715. array.push( renderItem );
  716. }
  717. }
  718. function projectObject( object, camera ) {
  719. if ( object.visible === false ) return;
  720. if ( object.layers.test( camera.layers ) ) {
  721. if ( object instanceof THREE.Light ) {
  722. lights.push( object );
  723. } else if ( object instanceof THREE.Sprite ) {
  724. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  725. sprites.push( object );
  726. }
  727. } else if ( object instanceof THREE.LensFlare ) {
  728. lensFlares.push( object );
  729. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  730. if ( _this.sortObjects === true ) {
  731. _vector3.setFromMatrixPosition( object.matrixWorld );
  732. _vector3.applyProjection( _projScreenMatrix );
  733. }
  734. pushRenderItem( object, null, object.material, _vector3.z, null );
  735. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  736. if ( object instanceof THREE.SkinnedMesh ) {
  737. object.skeleton.update();
  738. }
  739. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  740. var material = object.material;
  741. if ( material.visible === true ) {
  742. if ( _this.sortObjects === true ) {
  743. _vector3.setFromMatrixPosition( object.matrixWorld );
  744. _vector3.applyProjection( _projScreenMatrix );
  745. }
  746. var geometry = objects.update( object );
  747. if ( material instanceof THREE.MultiMaterial ) {
  748. var groups = geometry.groups;
  749. var materials = material.materials;
  750. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  751. var group = groups[ i ];
  752. var groupMaterial = materials[ group.materialIndex ];
  753. if ( groupMaterial.visible === true ) {
  754. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  755. }
  756. }
  757. } else {
  758. pushRenderItem( object, geometry, material, _vector3.z, null );
  759. }
  760. }
  761. }
  762. }
  763. }
  764. var children = object.children;
  765. for ( var i = 0, l = children.length; i < l; i ++ ) {
  766. projectObject( children[ i ], camera );
  767. }
  768. }
  769. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  770. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  771. var renderItem = renderList[ i ];
  772. var object = renderItem.object;
  773. var geometry = renderItem.geometry;
  774. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  775. var group = renderItem.group;
  776. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  777. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  778. if ( object instanceof THREE.ImmediateRenderObject ) {
  779. setMaterial( material );
  780. var program = setProgram( camera, fog, material, object );
  781. _currentGeometryProgram = '';
  782. object.render( function ( object ) {
  783. _this.renderBufferImmediate( object, program, material );
  784. } );
  785. } else {
  786. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  787. }
  788. }
  789. }
  790. function initMaterial( material, fog, object ) {
  791. var materialProperties = properties.get( material );
  792. var parameters = programCache.getParameters( material, _lights, fog, object );
  793. var code = programCache.getProgramCode( material, parameters );
  794. var program = materialProperties.program;
  795. var programChange = true;
  796. if ( program === undefined ) {
  797. // new material
  798. material.addEventListener( 'dispose', onMaterialDispose );
  799. } else if ( program.code !== code ) {
  800. // changed glsl or parameters
  801. releaseMaterialProgramReference( material );
  802. } else if ( parameters.shaderID !== undefined ) {
  803. // same glsl and uniform list
  804. return;
  805. } else {
  806. // only rebuild uniform list
  807. programChange = false;
  808. }
  809. if ( programChange ) {
  810. if ( parameters.shaderID ) {
  811. var shader = THREE.ShaderLib[ parameters.shaderID ];
  812. materialProperties.__webglShader = {
  813. name: material.type,
  814. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  815. vertexShader: shader.vertexShader,
  816. fragmentShader: shader.fragmentShader
  817. };
  818. } else {
  819. materialProperties.__webglShader = {
  820. name: material.type,
  821. uniforms: material.uniforms,
  822. vertexShader: material.vertexShader,
  823. fragmentShader: material.fragmentShader
  824. };
  825. }
  826. material.__webglShader = materialProperties.__webglShader;
  827. program = programCache.acquireProgram( material, parameters, code );
  828. materialProperties.program = program;
  829. material.program = program;
  830. }
  831. var attributes = program.getAttributes();
  832. if ( material.morphTargets ) {
  833. material.numSupportedMorphTargets = 0;
  834. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  835. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  836. material.numSupportedMorphTargets ++;
  837. }
  838. }
  839. }
  840. if ( material.morphNormals ) {
  841. material.numSupportedMorphNormals = 0;
  842. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  843. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  844. material.numSupportedMorphNormals ++;
  845. }
  846. }
  847. }
  848. materialProperties.uniformsList = [];
  849. var uniforms = materialProperties.__webglShader.uniforms,
  850. uniformLocations = materialProperties.program.getUniforms();
  851. for ( var u in uniforms ) {
  852. var location = uniformLocations[ u ];
  853. if ( location ) {
  854. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  855. }
  856. }
  857. if ( material instanceof THREE.MeshPhongMaterial ||
  858. material instanceof THREE.MeshLambertMaterial ||
  859. material instanceof THREE.MeshStandardMaterial ||
  860. material.lights ) {
  861. // store the light setup it was created for
  862. materialProperties.lightsHash = _lights.hash;
  863. // wire up the material to this renderer's lighting state
  864. uniforms.ambientLightColor.value = _lights.ambient;
  865. uniforms.directionalLights.value = _lights.directional;
  866. uniforms.spotLights.value = _lights.spot;
  867. uniforms.pointLights.value = _lights.point;
  868. uniforms.hemisphereLights.value = _lights.hemi;
  869. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  870. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  871. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  872. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  873. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  874. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  875. }
  876. // detect dynamic uniforms
  877. materialProperties.hasDynamicUniforms = false;
  878. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  879. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  880. if ( uniform.dynamic === true ) {
  881. materialProperties.hasDynamicUniforms = true;
  882. break;
  883. }
  884. }
  885. }
  886. function setMaterial( material ) {
  887. setMaterialFaces( material );
  888. if ( material.transparent === true ) {
  889. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  890. } else {
  891. state.setBlending( THREE.NoBlending );
  892. }
  893. state.setDepthFunc( material.depthFunc );
  894. state.setDepthTest( material.depthTest );
  895. state.setDepthWrite( material.depthWrite );
  896. state.setColorWrite( material.colorWrite );
  897. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  898. }
  899. function setMaterialFaces( material ) {
  900. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  901. state.setFlipSided( material.side === THREE.BackSide );
  902. }
  903. function setProgram( camera, fog, material, object ) {
  904. _usedTextureUnits = 0;
  905. var materialProperties = properties.get( material );
  906. if ( materialProperties.program === undefined ) {
  907. material.needsUpdate = true;
  908. }
  909. if ( materialProperties.lightsHash !== undefined &&
  910. materialProperties.lightsHash !== _lights.hash ) {
  911. material.needsUpdate = true;
  912. }
  913. if ( material.needsUpdate ) {
  914. initMaterial( material, fog, object );
  915. material.needsUpdate = false;
  916. }
  917. var refreshProgram = false;
  918. var refreshMaterial = false;
  919. var refreshLights = false;
  920. var program = materialProperties.program,
  921. p_uniforms = program.getUniforms(),
  922. m_uniforms = materialProperties.__webglShader.uniforms;
  923. if ( program.id !== _currentProgram ) {
  924. _gl.useProgram( program.program );
  925. _currentProgram = program.id;
  926. refreshProgram = true;
  927. refreshMaterial = true;
  928. refreshLights = true;
  929. }
  930. if ( material.id !== _currentMaterialId ) {
  931. _currentMaterialId = material.id;
  932. refreshMaterial = true;
  933. }
  934. if ( refreshProgram || camera !== _currentCamera ) {
  935. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  936. if ( capabilities.logarithmicDepthBuffer ) {
  937. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  938. }
  939. if ( camera !== _currentCamera ) {
  940. _currentCamera = camera;
  941. // lighting uniforms depend on the camera so enforce an update
  942. // now, in case this material supports lights - or later, when
  943. // the next material that does gets activated:
  944. refreshMaterial = true; // set to true on material change
  945. refreshLights = true; // remains set until update done
  946. }
  947. // load material specific uniforms
  948. // (shader material also gets them for the sake of genericity)
  949. if ( material instanceof THREE.ShaderMaterial ||
  950. material instanceof THREE.MeshPhongMaterial ||
  951. material instanceof THREE.MeshStandardMaterial ||
  952. material.envMap ) {
  953. if ( p_uniforms.cameraPosition !== undefined ) {
  954. _vector3.setFromMatrixPosition( camera.matrixWorld );
  955. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  956. }
  957. }
  958. if ( material instanceof THREE.MeshPhongMaterial ||
  959. material instanceof THREE.MeshLambertMaterial ||
  960. material instanceof THREE.MeshBasicMaterial ||
  961. material instanceof THREE.MeshStandardMaterial ||
  962. material instanceof THREE.ShaderMaterial ||
  963. material.skinning ) {
  964. if ( p_uniforms.viewMatrix !== undefined ) {
  965. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  966. }
  967. }
  968. if ( p_uniforms.toneMappingExposure !== undefined ) {
  969. _gl.uniform1f( p_uniforms.toneMappingExposure, _this.toneMappingExposure );
  970. }
  971. if ( p_uniforms.toneMappingWhitePoint !== undefined ) {
  972. _gl.uniform1f( p_uniforms.toneMappingWhitePoint, _this.toneMappingWhitePoint );
  973. }
  974. }
  975. // skinning uniforms must be set even if material didn't change
  976. // auto-setting of texture unit for bone texture must go before other textures
  977. // not sure why, but otherwise weird things happen
  978. if ( material.skinning ) {
  979. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  980. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  981. }
  982. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  983. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  984. }
  985. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  986. if ( p_uniforms.boneTexture !== undefined ) {
  987. var textureUnit = getTextureUnit();
  988. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  989. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  990. }
  991. if ( p_uniforms.boneTextureWidth !== undefined ) {
  992. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  993. }
  994. if ( p_uniforms.boneTextureHeight !== undefined ) {
  995. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  996. }
  997. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  998. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  999. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  1000. }
  1001. }
  1002. }
  1003. if ( refreshMaterial ) {
  1004. if ( material instanceof THREE.MeshPhongMaterial ||
  1005. material instanceof THREE.MeshLambertMaterial ||
  1006. material instanceof THREE.MeshStandardMaterial ||
  1007. material.lights ) {
  1008. // the current material requires lighting info
  1009. // note: all lighting uniforms are always set correctly
  1010. // they simply reference the renderer's state for their
  1011. // values
  1012. //
  1013. // use the current material's .needsUpdate flags to set
  1014. // the GL state when required
  1015. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1016. }
  1017. // refresh uniforms common to several materials
  1018. if ( fog && material.fog ) {
  1019. refreshUniformsFog( m_uniforms, fog );
  1020. }
  1021. if ( material instanceof THREE.MeshBasicMaterial ||
  1022. material instanceof THREE.MeshLambertMaterial ||
  1023. material instanceof THREE.MeshPhongMaterial ||
  1024. material instanceof THREE.MeshStandardMaterial ) {
  1025. refreshUniformsCommon( m_uniforms, material );
  1026. }
  1027. // refresh single material specific uniforms
  1028. if ( material instanceof THREE.LineBasicMaterial ) {
  1029. refreshUniformsLine( m_uniforms, material );
  1030. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1031. refreshUniformsLine( m_uniforms, material );
  1032. refreshUniformsDash( m_uniforms, material );
  1033. } else if ( material instanceof THREE.PointsMaterial ) {
  1034. refreshUniformsPoints( m_uniforms, material );
  1035. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1036. refreshUniformsLambert( m_uniforms, material );
  1037. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1038. refreshUniformsPhong( m_uniforms, material );
  1039. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  1040. refreshUniformsStandard( m_uniforms, material );
  1041. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1042. m_uniforms.mNear.value = camera.near;
  1043. m_uniforms.mFar.value = camera.far;
  1044. m_uniforms.opacity.value = material.opacity;
  1045. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1046. m_uniforms.opacity.value = material.opacity;
  1047. }
  1048. // load common uniforms
  1049. loadUniformsGeneric( materialProperties.uniformsList );
  1050. }
  1051. loadUniformsMatrices( p_uniforms, object );
  1052. if ( p_uniforms.modelMatrix !== undefined ) {
  1053. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  1054. }
  1055. if ( materialProperties.hasDynamicUniforms === true ) {
  1056. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  1057. }
  1058. return program;
  1059. }
  1060. function updateDynamicUniforms ( uniforms, object, camera ) {
  1061. var dynamicUniforms = [];
  1062. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1063. var uniform = uniforms[ j ][ 0 ];
  1064. var onUpdateCallback = uniform.onUpdateCallback;
  1065. if ( onUpdateCallback !== undefined ) {
  1066. onUpdateCallback.bind( uniform )( object, camera );
  1067. dynamicUniforms.push( uniforms[ j ] );
  1068. }
  1069. }
  1070. loadUniformsGeneric( dynamicUniforms );
  1071. }
  1072. // Uniforms (refresh uniforms objects)
  1073. function refreshUniformsCommon ( uniforms, material ) {
  1074. uniforms.opacity.value = material.opacity;
  1075. uniforms.diffuse.value = material.color;
  1076. if ( material.emissive ) {
  1077. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1078. }
  1079. uniforms.map.value = material.map;
  1080. uniforms.specularMap.value = material.specularMap;
  1081. uniforms.alphaMap.value = material.alphaMap;
  1082. if ( material.aoMap ) {
  1083. uniforms.aoMap.value = material.aoMap;
  1084. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1085. }
  1086. // uv repeat and offset setting priorities
  1087. // 1. color map
  1088. // 2. specular map
  1089. // 3. normal map
  1090. // 4. bump map
  1091. // 5. alpha map
  1092. // 6. emissive map
  1093. var uvScaleMap;
  1094. if ( material.map ) {
  1095. uvScaleMap = material.map;
  1096. } else if ( material.specularMap ) {
  1097. uvScaleMap = material.specularMap;
  1098. } else if ( material.displacementMap ) {
  1099. uvScaleMap = material.displacementMap;
  1100. } else if ( material.normalMap ) {
  1101. uvScaleMap = material.normalMap;
  1102. } else if ( material.bumpMap ) {
  1103. uvScaleMap = material.bumpMap;
  1104. } else if ( material.roughnessMap ) {
  1105. uvScaleMap = material.roughnessMap;
  1106. } else if ( material.metalnessMap ) {
  1107. uvScaleMap = material.metalnessMap;
  1108. } else if ( material.alphaMap ) {
  1109. uvScaleMap = material.alphaMap;
  1110. } else if ( material.emissiveMap ) {
  1111. uvScaleMap = material.emissiveMap;
  1112. }
  1113. if ( uvScaleMap !== undefined ) {
  1114. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  1115. uvScaleMap = uvScaleMap.texture;
  1116. }
  1117. var offset = uvScaleMap.offset;
  1118. var repeat = uvScaleMap.repeat;
  1119. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1120. }
  1121. uniforms.envMap.value = material.envMap;
  1122. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  1123. uniforms.reflectivity.value = material.reflectivity;
  1124. uniforms.refractionRatio.value = material.refractionRatio;
  1125. }
  1126. function refreshUniformsLine ( uniforms, material ) {
  1127. uniforms.diffuse.value = material.color;
  1128. uniforms.opacity.value = material.opacity;
  1129. }
  1130. function refreshUniformsDash ( uniforms, material ) {
  1131. uniforms.dashSize.value = material.dashSize;
  1132. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1133. uniforms.scale.value = material.scale;
  1134. }
  1135. function refreshUniformsPoints ( uniforms, material ) {
  1136. uniforms.diffuse.value = material.color;
  1137. uniforms.opacity.value = material.opacity;
  1138. uniforms.size.value = material.size * _pixelRatio;
  1139. uniforms.scale.value = _canvas.clientHeight / 2.0; // TODO: Cache this.
  1140. uniforms.map.value = material.map;
  1141. if ( material.map !== null ) {
  1142. var offset = material.map.offset;
  1143. var repeat = material.map.repeat;
  1144. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1145. }
  1146. }
  1147. function refreshUniformsFog ( uniforms, fog ) {
  1148. uniforms.fogColor.value = fog.color;
  1149. if ( fog instanceof THREE.Fog ) {
  1150. uniforms.fogNear.value = fog.near;
  1151. uniforms.fogFar.value = fog.far;
  1152. } else if ( fog instanceof THREE.FogExp2 ) {
  1153. uniforms.fogDensity.value = fog.density;
  1154. }
  1155. }
  1156. function refreshUniformsLambert ( uniforms, material ) {
  1157. if ( material.lightMap ) {
  1158. uniforms.lightMap.value = material.lightMap;
  1159. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1160. }
  1161. if ( material.emissiveMap ) {
  1162. uniforms.emissiveMap.value = material.emissiveMap;
  1163. }
  1164. }
  1165. function refreshUniformsPhong ( uniforms, material ) {
  1166. uniforms.specular.value = material.specular;
  1167. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1168. if ( material.lightMap ) {
  1169. uniforms.lightMap.value = material.lightMap;
  1170. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1171. }
  1172. if ( material.emissiveMap ) {
  1173. uniforms.emissiveMap.value = material.emissiveMap;
  1174. }
  1175. if ( material.bumpMap ) {
  1176. uniforms.bumpMap.value = material.bumpMap;
  1177. uniforms.bumpScale.value = material.bumpScale;
  1178. }
  1179. if ( material.normalMap ) {
  1180. uniforms.normalMap.value = material.normalMap;
  1181. uniforms.normalScale.value.copy( material.normalScale );
  1182. }
  1183. if ( material.displacementMap ) {
  1184. uniforms.displacementMap.value = material.displacementMap;
  1185. uniforms.displacementScale.value = material.displacementScale;
  1186. uniforms.displacementBias.value = material.displacementBias;
  1187. }
  1188. }
  1189. function refreshUniformsStandard ( uniforms, material ) {
  1190. uniforms.roughness.value = material.roughness;
  1191. uniforms.metalness.value = material.metalness;
  1192. if ( material.roughnessMap ) {
  1193. uniforms.roughnessMap.value = material.roughnessMap;
  1194. }
  1195. if ( material.metalnessMap ) {
  1196. uniforms.metalnessMap.value = material.metalnessMap;
  1197. }
  1198. if ( material.lightMap ) {
  1199. uniforms.lightMap.value = material.lightMap;
  1200. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1201. }
  1202. if ( material.emissiveMap ) {
  1203. uniforms.emissiveMap.value = material.emissiveMap;
  1204. }
  1205. if ( material.bumpMap ) {
  1206. uniforms.bumpMap.value = material.bumpMap;
  1207. uniforms.bumpScale.value = material.bumpScale;
  1208. }
  1209. if ( material.normalMap ) {
  1210. uniforms.normalMap.value = material.normalMap;
  1211. uniforms.normalScale.value.copy( material.normalScale );
  1212. }
  1213. if ( material.displacementMap ) {
  1214. uniforms.displacementMap.value = material.displacementMap;
  1215. uniforms.displacementScale.value = material.displacementScale;
  1216. uniforms.displacementBias.value = material.displacementBias;
  1217. }
  1218. if ( material.envMap ) {
  1219. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1220. uniforms.envMapIntensity.value = material.envMapIntensity;
  1221. }
  1222. }
  1223. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1224. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  1225. uniforms.ambientLightColor.needsUpdate = value;
  1226. uniforms.directionalLights.needsUpdate = value;
  1227. uniforms.pointLights.needsUpdate = value;
  1228. uniforms.spotLights.needsUpdate = value;
  1229. uniforms.hemisphereLights.needsUpdate = value;
  1230. }
  1231. // Uniforms (load to GPU)
  1232. function loadUniformsMatrices ( uniforms, object ) {
  1233. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  1234. if ( uniforms.normalMatrix ) {
  1235. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  1236. }
  1237. }
  1238. function getTextureUnit() {
  1239. var textureUnit = _usedTextureUnits;
  1240. if ( textureUnit >= capabilities.maxTextures ) {
  1241. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1242. }
  1243. _usedTextureUnits += 1;
  1244. return textureUnit;
  1245. }
  1246. function loadUniformsGeneric ( uniforms ) {
  1247. var texture, textureUnit;
  1248. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1249. var uniform = uniforms[ j ][ 0 ];
  1250. // needsUpdate property is not added to all uniforms.
  1251. if ( uniform.needsUpdate === false ) continue;
  1252. var type = uniform.type;
  1253. var value = uniform.value;
  1254. var location = uniforms[ j ][ 1 ];
  1255. switch ( type ) {
  1256. case '1i':
  1257. _gl.uniform1i( location, value );
  1258. break;
  1259. case '1f':
  1260. _gl.uniform1f( location, value );
  1261. break;
  1262. case '2f':
  1263. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  1264. break;
  1265. case '3f':
  1266. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  1267. break;
  1268. case '4f':
  1269. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  1270. break;
  1271. case '1iv':
  1272. _gl.uniform1iv( location, value );
  1273. break;
  1274. case '3iv':
  1275. _gl.uniform3iv( location, value );
  1276. break;
  1277. case '1fv':
  1278. _gl.uniform1fv( location, value );
  1279. break;
  1280. case '2fv':
  1281. _gl.uniform2fv( location, value );
  1282. break;
  1283. case '3fv':
  1284. _gl.uniform3fv( location, value );
  1285. break;
  1286. case '4fv':
  1287. _gl.uniform4fv( location, value );
  1288. break;
  1289. case 'Matrix2fv':
  1290. _gl.uniformMatrix2fv( location, false, value );
  1291. break;
  1292. case 'Matrix3fv':
  1293. _gl.uniformMatrix3fv( location, false, value );
  1294. break;
  1295. case 'Matrix4fv':
  1296. _gl.uniformMatrix4fv( location, false, value );
  1297. break;
  1298. //
  1299. case 'i':
  1300. // single integer
  1301. _gl.uniform1i( location, value );
  1302. break;
  1303. case 'f':
  1304. // single float
  1305. _gl.uniform1f( location, value );
  1306. break;
  1307. case 'v2':
  1308. // single THREE.Vector2
  1309. _gl.uniform2f( location, value.x, value.y );
  1310. break;
  1311. case 'v3':
  1312. // single THREE.Vector3
  1313. _gl.uniform3f( location, value.x, value.y, value.z );
  1314. break;
  1315. case 'v4':
  1316. // single THREE.Vector4
  1317. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  1318. break;
  1319. case 'c':
  1320. // single THREE.Color
  1321. _gl.uniform3f( location, value.r, value.g, value.b );
  1322. break;
  1323. /*
  1324. case 's':
  1325. // TODO: Optimize this.
  1326. for( var propertyName in uniform.properties ) {
  1327. var property = uniform.properties[ propertyName ];
  1328. var locationProperty = location[ propertyName ];
  1329. var valueProperty = value[ propertyName ];
  1330. switch( property.type ) {
  1331. case 'i':
  1332. _gl.uniform1i( locationProperty, valueProperty );
  1333. break;
  1334. case 'f':
  1335. _gl.uniform1f( locationProperty, valueProperty );
  1336. break;
  1337. case 'v2':
  1338. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  1339. break;
  1340. case 'v3':
  1341. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  1342. break;
  1343. case 'v4':
  1344. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  1345. break;
  1346. case 'c':
  1347. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  1348. break;
  1349. };
  1350. }
  1351. break;
  1352. */
  1353. case 'sa':
  1354. // TODO: Optimize this.
  1355. for ( var i = 0; i < value.length; i ++ ) {
  1356. for ( var propertyName in uniform.properties ) {
  1357. var property = uniform.properties[ propertyName ];
  1358. var locationProperty = location[ i ][ propertyName ];
  1359. var valueProperty = value[ i ][ propertyName ];
  1360. switch ( property.type ) {
  1361. case 'i':
  1362. _gl.uniform1i( locationProperty, valueProperty );
  1363. break;
  1364. case 'f':
  1365. _gl.uniform1f( locationProperty, valueProperty );
  1366. break;
  1367. case 'v2':
  1368. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  1369. break;
  1370. case 'v3':
  1371. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  1372. break;
  1373. case 'v4':
  1374. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  1375. break;
  1376. case 'c':
  1377. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  1378. break;
  1379. case 'm4':
  1380. _gl.uniformMatrix4fv( locationProperty, false, valueProperty.elements );
  1381. break;
  1382. }
  1383. }
  1384. }
  1385. break;
  1386. case 'iv1':
  1387. // flat array of integers (JS or typed array)
  1388. _gl.uniform1iv( location, value );
  1389. break;
  1390. case 'iv':
  1391. // flat array of integers with 3 x N size (JS or typed array)
  1392. _gl.uniform3iv( location, value );
  1393. break;
  1394. case 'fv1':
  1395. // flat array of floats (JS or typed array)
  1396. _gl.uniform1fv( location, value );
  1397. break;
  1398. case 'fv':
  1399. // flat array of floats with 3 x N size (JS or typed array)
  1400. _gl.uniform3fv( location, value );
  1401. break;
  1402. case 'v2v':
  1403. // array of THREE.Vector2
  1404. if ( uniform._array === undefined ) {
  1405. uniform._array = new Float32Array( 2 * value.length );
  1406. }
  1407. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  1408. uniform._array[ i2 + 0 ] = value[ i ].x;
  1409. uniform._array[ i2 + 1 ] = value[ i ].y;
  1410. }
  1411. _gl.uniform2fv( location, uniform._array );
  1412. break;
  1413. case 'v3v':
  1414. // array of THREE.Vector3
  1415. if ( uniform._array === undefined ) {
  1416. uniform._array = new Float32Array( 3 * value.length );
  1417. }
  1418. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  1419. uniform._array[ i3 + 0 ] = value[ i ].x;
  1420. uniform._array[ i3 + 1 ] = value[ i ].y;
  1421. uniform._array[ i3 + 2 ] = value[ i ].z;
  1422. }
  1423. _gl.uniform3fv( location, uniform._array );
  1424. break;
  1425. case 'v4v':
  1426. // array of THREE.Vector4
  1427. if ( uniform._array === undefined ) {
  1428. uniform._array = new Float32Array( 4 * value.length );
  1429. }
  1430. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  1431. uniform._array[ i4 + 0 ] = value[ i ].x;
  1432. uniform._array[ i4 + 1 ] = value[ i ].y;
  1433. uniform._array[ i4 + 2 ] = value[ i ].z;
  1434. uniform._array[ i4 + 3 ] = value[ i ].w;
  1435. }
  1436. _gl.uniform4fv( location, uniform._array );
  1437. break;
  1438. case 'm2':
  1439. // single THREE.Matrix2
  1440. _gl.uniformMatrix2fv( location, false, value.elements );
  1441. break;
  1442. case 'm3':
  1443. // single THREE.Matrix3
  1444. _gl.uniformMatrix3fv( location, false, value.elements );
  1445. break;
  1446. case 'm3v':
  1447. // array of THREE.Matrix3
  1448. if ( uniform._array === undefined ) {
  1449. uniform._array = new Float32Array( 9 * value.length );
  1450. }
  1451. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1452. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  1453. }
  1454. _gl.uniformMatrix3fv( location, false, uniform._array );
  1455. break;
  1456. case 'm4':
  1457. // single THREE.Matrix4
  1458. _gl.uniformMatrix4fv( location, false, value.elements );
  1459. break;
  1460. case 'm4v':
  1461. // array of THREE.Matrix4
  1462. if ( uniform._array === undefined ) {
  1463. uniform._array = new Float32Array( 16 * value.length );
  1464. }
  1465. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1466. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  1467. }
  1468. _gl.uniformMatrix4fv( location, false, uniform._array );
  1469. break;
  1470. case 't':
  1471. // single THREE.Texture (2d or cube)
  1472. texture = value;
  1473. textureUnit = getTextureUnit();
  1474. _gl.uniform1i( location, textureUnit );
  1475. if ( ! texture ) continue;
  1476. if ( texture instanceof THREE.CubeTexture ||
  1477. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1478. // CompressedTexture can have Array in image :/
  1479. setCubeTexture( texture, textureUnit );
  1480. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1481. setCubeTextureDynamic( texture.texture, textureUnit );
  1482. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1483. _this.setTexture( texture.texture, textureUnit );
  1484. } else {
  1485. _this.setTexture( texture, textureUnit );
  1486. }
  1487. break;
  1488. case 'tv':
  1489. // array of THREE.Texture (2d or cube)
  1490. if ( uniform._array === undefined ) {
  1491. uniform._array = [];
  1492. }
  1493. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1494. uniform._array[ i ] = getTextureUnit();
  1495. }
  1496. _gl.uniform1iv( location, uniform._array );
  1497. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1498. texture = uniform.value[ i ];
  1499. textureUnit = uniform._array[ i ];
  1500. if ( ! texture ) continue;
  1501. if ( texture instanceof THREE.CubeTexture ||
  1502. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  1503. // CompressedTexture can have Array in image :/
  1504. setCubeTexture( texture, textureUnit );
  1505. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1506. _this.setTexture( texture.texture, textureUnit );
  1507. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1508. setCubeTextureDynamic( texture.texture, textureUnit );
  1509. } else {
  1510. _this.setTexture( texture, textureUnit );
  1511. }
  1512. }
  1513. break;
  1514. default:
  1515. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  1516. }
  1517. }
  1518. }
  1519. function setupLights ( lights, camera ) {
  1520. var l, ll, light,
  1521. r = 0, g = 0, b = 0,
  1522. color,
  1523. intensity,
  1524. distance,
  1525. viewMatrix = camera.matrixWorldInverse,
  1526. directionalLength = 0,
  1527. pointLength = 0,
  1528. spotLength = 0,
  1529. hemiLength = 0,
  1530. shadowsLength = 0;
  1531. _lights.shadowsPointLight = 0;
  1532. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1533. light = lights[ l ];
  1534. color = light.color;
  1535. intensity = light.intensity;
  1536. distance = light.distance;
  1537. if ( light instanceof THREE.AmbientLight ) {
  1538. r += color.r * intensity;
  1539. g += color.g * intensity;
  1540. b += color.b * intensity;
  1541. } else if ( light instanceof THREE.DirectionalLight ) {
  1542. var uniforms = lightCache.get( light );
  1543. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1544. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1545. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1546. uniforms.direction.sub( _vector3 );
  1547. uniforms.direction.transformDirection( viewMatrix );
  1548. uniforms.shadow = light.castShadow;
  1549. if ( light.castShadow ) {
  1550. uniforms.shadowBias = light.shadow.bias;
  1551. uniforms.shadowRadius = light.shadow.radius;
  1552. uniforms.shadowMapSize = light.shadow.mapSize;
  1553. _lights.shadows[ shadowsLength ++ ] = light;
  1554. }
  1555. _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
  1556. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1557. _lights.directional[ directionalLength ++ ] = uniforms;
  1558. } else if ( light instanceof THREE.SpotLight ) {
  1559. var uniforms = lightCache.get( light );
  1560. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1561. uniforms.position.applyMatrix4( viewMatrix );
  1562. uniforms.color.copy( color ).multiplyScalar( intensity );
  1563. uniforms.distance = distance;
  1564. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1565. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1566. uniforms.direction.sub( _vector3 );
  1567. uniforms.direction.transformDirection( viewMatrix );
  1568. uniforms.coneCos = Math.cos( light.angle );
  1569. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1570. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1571. uniforms.shadow = light.castShadow;
  1572. if ( light.castShadow ) {
  1573. uniforms.shadowBias = light.shadow.bias;
  1574. uniforms.shadowRadius = light.shadow.radius;
  1575. uniforms.shadowMapSize = light.shadow.mapSize;
  1576. _lights.shadows[ shadowsLength ++ ] = light;
  1577. }
  1578. _lights.spotShadowMap[ spotLength ] = light.shadow.map;
  1579. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1580. _lights.spot[ spotLength ++ ] = uniforms;
  1581. } else if ( light instanceof THREE.PointLight ) {
  1582. var uniforms = lightCache.get( light );
  1583. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1584. uniforms.position.applyMatrix4( viewMatrix );
  1585. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1586. uniforms.distance = light.distance;
  1587. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1588. uniforms.shadow = light.castShadow;
  1589. if ( light.castShadow ) {
  1590. uniforms.shadowBias = light.shadow.bias;
  1591. uniforms.shadowRadius = light.shadow.radius;
  1592. uniforms.shadowMapSize = light.shadow.mapSize;
  1593. _lights.shadows[ shadowsLength ++ ] = light;
  1594. }
  1595. _lights.pointShadowMap[ pointLength ] = light.shadow.map;
  1596. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1597. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  1598. }
  1599. // for point lights we set the shadow matrix to be a translation-only matrix
  1600. // equal to inverse of the light's position
  1601. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1602. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1603. _lights.point[ pointLength ++ ] = uniforms;
  1604. } else if ( light instanceof THREE.HemisphereLight ) {
  1605. var uniforms = lightCache.get( light );
  1606. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1607. uniforms.direction.transformDirection( viewMatrix );
  1608. uniforms.direction.normalize();
  1609. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1610. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1611. _lights.hemi[ hemiLength ++ ] = uniforms;
  1612. }
  1613. }
  1614. _lights.ambient[ 0 ] = r;
  1615. _lights.ambient[ 1 ] = g;
  1616. _lights.ambient[ 2 ] = b;
  1617. _lights.directional.length = directionalLength;
  1618. _lights.spot.length = spotLength;
  1619. _lights.point.length = pointLength;
  1620. _lights.hemi.length = hemiLength;
  1621. _lights.shadows.length = shadowsLength;
  1622. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + shadowsLength;
  1623. }
  1624. // GL state setting
  1625. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1626. if ( cullFace === THREE.CullFaceNone ) {
  1627. state.disable( _gl.CULL_FACE );
  1628. } else {
  1629. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  1630. _gl.frontFace( _gl.CW );
  1631. } else {
  1632. _gl.frontFace( _gl.CCW );
  1633. }
  1634. if ( cullFace === THREE.CullFaceBack ) {
  1635. _gl.cullFace( _gl.BACK );
  1636. } else if ( cullFace === THREE.CullFaceFront ) {
  1637. _gl.cullFace( _gl.FRONT );
  1638. } else {
  1639. _gl.cullFace( _gl.FRONT_AND_BACK );
  1640. }
  1641. state.enable( _gl.CULL_FACE );
  1642. }
  1643. };
  1644. // Textures
  1645. function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
  1646. var extension;
  1647. if ( isPowerOfTwoImage ) {
  1648. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  1649. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  1650. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  1651. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  1652. } else {
  1653. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  1654. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  1655. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  1656. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  1657. }
  1658. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  1659. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  1660. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  1661. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  1662. }
  1663. }
  1664. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  1665. if ( extension ) {
  1666. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  1667. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  1668. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  1669. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  1670. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  1671. }
  1672. }
  1673. }
  1674. function uploadTexture( textureProperties, texture, slot ) {
  1675. if ( textureProperties.__webglInit === undefined ) {
  1676. textureProperties.__webglInit = true;
  1677. texture.addEventListener( 'dispose', onTextureDispose );
  1678. textureProperties.__webglTexture = _gl.createTexture();
  1679. _infoMemory.textures ++;
  1680. }
  1681. state.activeTexture( _gl.TEXTURE0 + slot );
  1682. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1683. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1684. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  1685. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  1686. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  1687. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  1688. image = makePowerOfTwo( image );
  1689. }
  1690. var isPowerOfTwoImage = isPowerOfTwo( image ),
  1691. glFormat = paramThreeToGL( texture.format ),
  1692. glType = paramThreeToGL( texture.type );
  1693. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  1694. var mipmap, mipmaps = texture.mipmaps;
  1695. if ( texture instanceof THREE.DataTexture ) {
  1696. // use manually created mipmaps if available
  1697. // if there are no manual mipmaps
  1698. // set 0 level mipmap and then use GL to generate other mipmap levels
  1699. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1700. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1701. mipmap = mipmaps[ i ];
  1702. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1703. }
  1704. texture.generateMipmaps = false;
  1705. } else {
  1706. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  1707. }
  1708. } else if ( texture instanceof THREE.CompressedTexture ) {
  1709. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1710. mipmap = mipmaps[ i ];
  1711. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1712. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1713. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1714. } else {
  1715. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  1716. }
  1717. } else {
  1718. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1719. }
  1720. }
  1721. } else {
  1722. // regular Texture (image, video, canvas)
  1723. // use manually created mipmaps if available
  1724. // if there are no manual mipmaps
  1725. // set 0 level mipmap and then use GL to generate other mipmap levels
  1726. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1727. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1728. mipmap = mipmaps[ i ];
  1729. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  1730. }
  1731. texture.generateMipmaps = false;
  1732. } else {
  1733. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  1734. }
  1735. }
  1736. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1737. textureProperties.__version = texture.version;
  1738. if ( texture.onUpdate ) texture.onUpdate( texture );
  1739. }
  1740. this.setTexture = function ( texture, slot ) {
  1741. var textureProperties = properties.get( texture );
  1742. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1743. var image = texture.image;
  1744. if ( image === undefined ) {
  1745. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  1746. return;
  1747. }
  1748. if ( image.complete === false ) {
  1749. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  1750. return;
  1751. }
  1752. uploadTexture( textureProperties, texture, slot );
  1753. return;
  1754. }
  1755. state.activeTexture( _gl.TEXTURE0 + slot );
  1756. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1757. };
  1758. function clampToMaxSize ( image, maxSize ) {
  1759. if ( image.width > maxSize || image.height > maxSize ) {
  1760. // Warning: Scaling through the canvas will only work with images that use
  1761. // premultiplied alpha.
  1762. var scale = maxSize / Math.max( image.width, image.height );
  1763. var canvas = document.createElement( 'canvas' );
  1764. canvas.width = Math.floor( image.width * scale );
  1765. canvas.height = Math.floor( image.height * scale );
  1766. var context = canvas.getContext( '2d' );
  1767. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  1768. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1769. return canvas;
  1770. }
  1771. return image;
  1772. }
  1773. function isPowerOfTwo( image ) {
  1774. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  1775. }
  1776. function textureNeedsPowerOfTwo( texture ) {
  1777. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  1778. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  1779. return false;
  1780. }
  1781. function makePowerOfTwo( image ) {
  1782. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  1783. var canvas = document.createElement( 'canvas' );
  1784. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  1785. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  1786. var context = canvas.getContext( '2d' );
  1787. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  1788. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1789. return canvas;
  1790. }
  1791. return image;
  1792. }
  1793. function setCubeTexture ( texture, slot ) {
  1794. var textureProperties = properties.get( texture );
  1795. if ( texture.image.length === 6 ) {
  1796. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1797. if ( ! textureProperties.__image__webglTextureCube ) {
  1798. texture.addEventListener( 'dispose', onTextureDispose );
  1799. textureProperties.__image__webglTextureCube = _gl.createTexture();
  1800. _infoMemory.textures ++;
  1801. }
  1802. state.activeTexture( _gl.TEXTURE0 + slot );
  1803. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1804. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1805. var isCompressed = texture instanceof THREE.CompressedTexture;
  1806. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  1807. var cubeImage = [];
  1808. for ( var i = 0; i < 6; i ++ ) {
  1809. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  1810. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  1811. } else {
  1812. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  1813. }
  1814. }
  1815. var image = cubeImage[ 0 ],
  1816. isPowerOfTwoImage = isPowerOfTwo( image ),
  1817. glFormat = paramThreeToGL( texture.format ),
  1818. glType = paramThreeToGL( texture.type );
  1819. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  1820. for ( var i = 0; i < 6; i ++ ) {
  1821. if ( ! isCompressed ) {
  1822. if ( isDataTexture ) {
  1823. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  1824. } else {
  1825. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  1826. }
  1827. } else {
  1828. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  1829. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  1830. mipmap = mipmaps[ j ];
  1831. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1832. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1833. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1834. } else {
  1835. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  1836. }
  1837. } else {
  1838. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1839. }
  1840. }
  1841. }
  1842. }
  1843. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  1844. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  1845. }
  1846. textureProperties.__version = texture.version;
  1847. if ( texture.onUpdate ) texture.onUpdate( texture );
  1848. } else {
  1849. state.activeTexture( _gl.TEXTURE0 + slot );
  1850. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1851. }
  1852. }
  1853. }
  1854. function setCubeTextureDynamic ( texture, slot ) {
  1855. state.activeTexture( _gl.TEXTURE0 + slot );
  1856. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  1857. }
  1858. // Render targets
  1859. // Setup storage for target texture and bind it to correct framebuffer
  1860. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  1861. var glFormat = paramThreeToGL( renderTarget.texture.format );
  1862. var glType = paramThreeToGL( renderTarget.texture.type );
  1863. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  1864. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1865. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  1866. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1867. }
  1868. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  1869. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  1870. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  1871. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  1872. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  1873. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1874. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  1875. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  1876. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1877. } else {
  1878. // FIXME: We don't support !depth !stencil
  1879. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  1880. }
  1881. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  1882. }
  1883. // Setup GL resources for a non-texture depth buffer
  1884. function setupDepthRenderbuffer( renderTarget ) {
  1885. var renderTargetProperties = properties.get( renderTarget );
  1886. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1887. if ( isCube ) {
  1888. renderTargetProperties.__webglDepthbuffer = [];
  1889. for ( var i = 0; i < 6; i ++ ) {
  1890. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  1891. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  1892. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  1893. }
  1894. } else {
  1895. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  1896. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  1897. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  1898. }
  1899. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1900. }
  1901. // Set up GL resources for the render target
  1902. function setupRenderTarget( renderTarget ) {
  1903. var renderTargetProperties = properties.get( renderTarget );
  1904. var textureProperties = properties.get( renderTarget.texture );
  1905. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  1906. textureProperties.__webglTexture = _gl.createTexture();
  1907. _infoMemory.textures ++;
  1908. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1909. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  1910. // Setup framebuffer
  1911. if ( isCube ) {
  1912. renderTargetProperties.__webglFramebuffer = [];
  1913. for ( var i = 0; i < 6; i ++ ) {
  1914. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  1915. }
  1916. } else {
  1917. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  1918. }
  1919. // Setup color buffer
  1920. if ( isCube ) {
  1921. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  1922. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  1923. for ( var i = 0; i < 6; i ++ ) {
  1924. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  1925. }
  1926. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  1927. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  1928. } else {
  1929. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1930. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  1931. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  1932. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1933. state.bindTexture( _gl.TEXTURE_2D, null );
  1934. }
  1935. // Setup depth and stencil buffers
  1936. if ( renderTarget.depthBuffer ) {
  1937. setupDepthRenderbuffer( renderTarget );
  1938. }
  1939. }
  1940. this.getCurrentRenderTarget = function() {
  1941. return _currentRenderTarget;
  1942. }
  1943. this.setRenderTarget = function ( renderTarget ) {
  1944. _currentRenderTarget = renderTarget;
  1945. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1946. setupRenderTarget( renderTarget );
  1947. }
  1948. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1949. var framebuffer;
  1950. if ( renderTarget ) {
  1951. var renderTargetProperties = properties.get( renderTarget );
  1952. if ( isCube ) {
  1953. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  1954. } else {
  1955. framebuffer = renderTargetProperties.__webglFramebuffer;
  1956. }
  1957. _currentScissor.copy( renderTarget.scissor );
  1958. _currentScissorTest = renderTarget.scissorTest;
  1959. _currentViewport.copy( renderTarget.viewport );
  1960. } else {
  1961. framebuffer = null;
  1962. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1963. _currentScissorTest = _scissorTest;
  1964. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1965. }
  1966. if ( _currentFramebuffer !== framebuffer ) {
  1967. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1968. _currentFramebuffer = framebuffer;
  1969. }
  1970. state.scissor( _currentScissor );
  1971. state.setScissorTest( _currentScissorTest );
  1972. state.viewport( _currentViewport );
  1973. if ( isCube ) {
  1974. var textureProperties = properties.get( renderTarget.texture );
  1975. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  1976. }
  1977. };
  1978. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1979. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  1980. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1981. return;
  1982. }
  1983. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1984. if ( framebuffer ) {
  1985. var restore = false;
  1986. if ( framebuffer !== _currentFramebuffer ) {
  1987. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1988. restore = true;
  1989. }
  1990. try {
  1991. var texture = renderTarget.texture;
  1992. if ( texture.format !== THREE.RGBAFormat
  1993. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1994. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1995. return;
  1996. }
  1997. if ( texture.type !== THREE.UnsignedByteType
  1998. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  1999. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  2000. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  2001. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  2002. return;
  2003. }
  2004. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  2005. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  2006. } else {
  2007. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  2008. }
  2009. } finally {
  2010. if ( restore ) {
  2011. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  2012. }
  2013. }
  2014. }
  2015. };
  2016. function updateRenderTargetMipmap( renderTarget ) {
  2017. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  2018. var texture = properties.get( renderTarget.texture ).__webglTexture;
  2019. state.bindTexture( target, texture );
  2020. _gl.generateMipmap( target );
  2021. state.bindTexture( target, null );
  2022. }
  2023. // Fallback filters for non-power-of-2 textures
  2024. function filterFallback ( f ) {
  2025. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  2026. return _gl.NEAREST;
  2027. }
  2028. return _gl.LINEAR;
  2029. }
  2030. // Map three.js constants to WebGL constants
  2031. function paramThreeToGL ( p ) {
  2032. var extension;
  2033. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  2034. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  2035. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  2036. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  2037. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  2038. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  2039. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  2040. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  2041. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  2042. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  2043. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  2044. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  2045. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  2046. if ( p === THREE.ByteType ) return _gl.BYTE;
  2047. if ( p === THREE.ShortType ) return _gl.SHORT;
  2048. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  2049. if ( p === THREE.IntType ) return _gl.INT;
  2050. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  2051. if ( p === THREE.FloatType ) return _gl.FLOAT;
  2052. extension = extensions.get( 'OES_texture_half_float' );
  2053. if ( extension !== null ) {
  2054. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  2055. }
  2056. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  2057. if ( p === THREE.RGBFormat ) return _gl.RGB;
  2058. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  2059. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  2060. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  2061. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  2062. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  2063. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  2064. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  2065. if ( p === THREE.OneFactor ) return _gl.ONE;
  2066. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  2067. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  2068. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  2069. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  2070. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  2071. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  2072. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  2073. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  2074. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  2075. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  2076. if ( extension !== null ) {
  2077. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  2078. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  2079. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  2080. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  2081. }
  2082. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  2083. if ( extension !== null ) {
  2084. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  2085. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  2086. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  2087. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  2088. }
  2089. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  2090. if ( extension !== null ) {
  2091. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  2092. }
  2093. extension = extensions.get( 'EXT_blend_minmax' );
  2094. if ( extension !== null ) {
  2095. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  2096. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  2097. }
  2098. return 0;
  2099. }
  2100. };
粤ICP备19079148号