WebGLRenderer.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. import {
  2. REVISION,
  3. RGBAFormat,
  4. HalfFloatType,
  5. FloatType,
  6. UnsignedByteType,
  7. TriangleFanDrawMode,
  8. TriangleStripDrawMode,
  9. TrianglesDrawMode,
  10. LinearToneMapping,
  11. BackSide
  12. } from '../constants.js';
  13. import { _Math } from '../math/Math.js';
  14. import { DataTexture } from '../textures/DataTexture.js';
  15. import { Frustum } from '../math/Frustum.js';
  16. import { Matrix4 } from '../math/Matrix4.js';
  17. import { ShaderLib } from './shaders/ShaderLib.js';
  18. import { UniformsLib } from './shaders/UniformsLib.js';
  19. import { UniformsUtils } from './shaders/UniformsUtils.js';
  20. import { Vector3 } from '../math/Vector3.js';
  21. import { Vector4 } from '../math/Vector4.js';
  22. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  23. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  24. import { WebGLBackground } from './webgl/WebGLBackground.js';
  25. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  26. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  27. import { WebGLClipping } from './webgl/WebGLClipping.js';
  28. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  29. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  30. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  31. import { WebGLInfo } from './webgl/WebGLInfo.js';
  32. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  33. import { WebGLObjects } from './webgl/WebGLObjects.js';
  34. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  35. import { WebGLProperties } from './webgl/WebGLProperties.js';
  36. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  37. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  38. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  39. import { WebGLState } from './webgl/WebGLState.js';
  40. import { WebGLTextures } from './webgl/WebGLTextures.js';
  41. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  42. import { WebGLUtils } from './webgl/WebGLUtils.js';
  43. import { WebVRManager } from './webvr/WebVRManager.js';
  44. import { WebXRManager } from './webvr/WebXRManager.js';
  45. /**
  46. * @author supereggbert / http://www.paulbrunt.co.uk/
  47. * @author mrdoob / http://mrdoob.com/
  48. * @author alteredq / http://alteredqualia.com/
  49. * @author szimek / https://github.com/szimek/
  50. * @author tschw
  51. */
  52. function WebGLRenderer( parameters ) {
  53. console.log( 'THREE.WebGLRenderer', REVISION );
  54. parameters = parameters || {};
  55. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  56. _context = parameters.context !== undefined ? parameters.context : null,
  57. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  58. _depth = parameters.depth !== undefined ? parameters.depth : true,
  59. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  60. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  61. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  62. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  63. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  64. var currentRenderList = null;
  65. var currentRenderState = null;
  66. // public properties
  67. this.domElement = _canvas;
  68. this.context = null;
  69. // clearing
  70. this.autoClear = true;
  71. this.autoClearColor = true;
  72. this.autoClearDepth = true;
  73. this.autoClearStencil = true;
  74. // scene graph
  75. this.sortObjects = true;
  76. // user-defined clipping
  77. this.clippingPlanes = [];
  78. this.localClippingEnabled = false;
  79. // physically based shading
  80. this.gammaFactor = 2.0; // for backwards compatibility
  81. this.gammaInput = false;
  82. this.gammaOutput = false;
  83. // physical lights
  84. this.physicallyCorrectLights = false;
  85. // tone mapping
  86. this.toneMapping = LinearToneMapping;
  87. this.toneMappingExposure = 1.0;
  88. this.toneMappingWhitePoint = 1.0;
  89. // morphs
  90. this.maxMorphTargets = 8;
  91. this.maxMorphNormals = 4;
  92. // internal properties
  93. var _this = this,
  94. _isContextLost = false,
  95. // internal state cache
  96. _framebuffer = null,
  97. _currentRenderTarget = null,
  98. _currentFramebuffer = null,
  99. _currentMaterialId = - 1,
  100. _currentGeometryProgram = '',
  101. _currentCamera = null,
  102. _currentArrayCamera = null,
  103. _currentViewport = new Vector4(),
  104. _currentScissor = new Vector4(),
  105. _currentScissorTest = null,
  106. //
  107. _usedTextureUnits = 0,
  108. //
  109. _width = _canvas.width,
  110. _height = _canvas.height,
  111. _pixelRatio = 1,
  112. _viewport = new Vector4( 0, 0, _width, _height ),
  113. _scissor = new Vector4( 0, 0, _width, _height ),
  114. _scissorTest = false,
  115. // frustum
  116. _frustum = new Frustum(),
  117. // clipping
  118. _clipping = new WebGLClipping(),
  119. _clippingEnabled = false,
  120. _localClippingEnabled = false,
  121. // camera matrices cache
  122. _projScreenMatrix = new Matrix4(),
  123. _vector3 = new Vector3();
  124. function getTargetPixelRatio() {
  125. return _currentRenderTarget === null ? _pixelRatio : 1;
  126. }
  127. // initialize
  128. var _gl;
  129. try {
  130. var contextAttributes = {
  131. alpha: _alpha,
  132. depth: _depth,
  133. stencil: _stencil,
  134. antialias: _antialias,
  135. premultipliedAlpha: _premultipliedAlpha,
  136. preserveDrawingBuffer: _preserveDrawingBuffer,
  137. powerPreference: _powerPreference
  138. };
  139. // event listeners must be registered before WebGL context is created, see #12753
  140. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  141. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  142. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  143. if ( _gl === null ) {
  144. if ( _canvas.getContext( 'webgl' ) !== null ) {
  145. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  146. } else {
  147. throw new Error( 'Error creating WebGL context.' );
  148. }
  149. }
  150. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  151. if ( _gl.getShaderPrecisionFormat === undefined ) {
  152. _gl.getShaderPrecisionFormat = function () {
  153. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  154. };
  155. }
  156. } catch ( error ) {
  157. console.error( 'THREE.WebGLRenderer: ' + error.message );
  158. }
  159. var extensions, capabilities, state, info;
  160. var properties, textures, attributes, geometries, objects;
  161. var programCache, renderLists, renderStates;
  162. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  163. var utils;
  164. function initGLContext() {
  165. extensions = new WebGLExtensions( _gl );
  166. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  167. if ( ! capabilities.isWebGL2 ) {
  168. extensions.get( 'WEBGL_depth_texture' );
  169. extensions.get( 'OES_texture_float' );
  170. extensions.get( 'OES_texture_half_float' );
  171. extensions.get( 'OES_texture_half_float_linear' );
  172. extensions.get( 'OES_standard_derivatives' );
  173. extensions.get( 'OES_element_index_uint' );
  174. extensions.get( 'ANGLE_instanced_arrays' );
  175. }
  176. extensions.get( 'OES_texture_float_linear' );
  177. utils = new WebGLUtils( _gl, extensions, capabilities );
  178. state = new WebGLState( _gl, extensions, utils, capabilities );
  179. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  180. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  181. info = new WebGLInfo( _gl );
  182. properties = new WebGLProperties();
  183. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  184. attributes = new WebGLAttributes( _gl );
  185. geometries = new WebGLGeometries( _gl, attributes, info );
  186. objects = new WebGLObjects( geometries, info );
  187. morphtargets = new WebGLMorphtargets( _gl );
  188. programCache = new WebGLPrograms( _this, extensions, capabilities );
  189. renderLists = new WebGLRenderLists();
  190. renderStates = new WebGLRenderStates();
  191. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  192. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  193. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  194. info.programs = programCache.programs;
  195. _this.context = _gl;
  196. _this.capabilities = capabilities;
  197. _this.extensions = extensions;
  198. _this.properties = properties;
  199. _this.renderLists = renderLists;
  200. _this.state = state;
  201. _this.info = info;
  202. }
  203. initGLContext();
  204. // vr
  205. var vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  206. this.vr = vr;
  207. // shadow map
  208. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  209. this.shadowMap = shadowMap;
  210. // API
  211. this.getContext = function () {
  212. return _gl;
  213. };
  214. this.getContextAttributes = function () {
  215. return _gl.getContextAttributes();
  216. };
  217. this.forceContextLoss = function () {
  218. var extension = extensions.get( 'WEBGL_lose_context' );
  219. if ( extension ) extension.loseContext();
  220. };
  221. this.forceContextRestore = function () {
  222. var extension = extensions.get( 'WEBGL_lose_context' );
  223. if ( extension ) extension.restoreContext();
  224. };
  225. this.getPixelRatio = function () {
  226. return _pixelRatio;
  227. };
  228. this.setPixelRatio = function ( value ) {
  229. if ( value === undefined ) return;
  230. _pixelRatio = value;
  231. this.setSize( _width, _height, false );
  232. };
  233. this.getSize = function () {
  234. return {
  235. width: _width,
  236. height: _height
  237. };
  238. };
  239. this.setSize = function ( width, height, updateStyle ) {
  240. if ( vr.isPresenting() ) {
  241. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  242. return;
  243. }
  244. _width = width;
  245. _height = height;
  246. _canvas.width = width * _pixelRatio;
  247. _canvas.height = height * _pixelRatio;
  248. if ( updateStyle !== false ) {
  249. _canvas.style.width = width + 'px';
  250. _canvas.style.height = height + 'px';
  251. }
  252. this.setViewport( 0, 0, width, height );
  253. };
  254. this.getDrawingBufferSize = function () {
  255. return {
  256. width: _width * _pixelRatio,
  257. height: _height * _pixelRatio
  258. };
  259. };
  260. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  261. _width = width;
  262. _height = height;
  263. _pixelRatio = pixelRatio;
  264. _canvas.width = width * pixelRatio;
  265. _canvas.height = height * pixelRatio;
  266. this.setViewport( 0, 0, width, height );
  267. };
  268. this.getCurrentViewport = function () {
  269. return _currentViewport;
  270. };
  271. this.setViewport = function ( x, y, width, height ) {
  272. _viewport.set( x, _height - y - height, width, height );
  273. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  274. };
  275. this.setScissor = function ( x, y, width, height ) {
  276. _scissor.set( x, _height - y - height, width, height );
  277. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  278. };
  279. this.setScissorTest = function ( boolean ) {
  280. state.setScissorTest( _scissorTest = boolean );
  281. };
  282. // Clearing
  283. this.getClearColor = function () {
  284. return background.getClearColor();
  285. };
  286. this.setClearColor = function () {
  287. background.setClearColor.apply( background, arguments );
  288. };
  289. this.getClearAlpha = function () {
  290. return background.getClearAlpha();
  291. };
  292. this.setClearAlpha = function () {
  293. background.setClearAlpha.apply( background, arguments );
  294. };
  295. this.clear = function ( color, depth, stencil ) {
  296. var bits = 0;
  297. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  298. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  299. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  300. _gl.clear( bits );
  301. };
  302. this.clearColor = function () {
  303. this.clear( true, false, false );
  304. };
  305. this.clearDepth = function () {
  306. this.clear( false, true, false );
  307. };
  308. this.clearStencil = function () {
  309. this.clear( false, false, true );
  310. };
  311. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  312. this.setRenderTarget( renderTarget );
  313. this.clear( color, depth, stencil );
  314. };
  315. //
  316. this.dispose = function () {
  317. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  318. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  319. renderLists.dispose();
  320. renderStates.dispose();
  321. properties.dispose();
  322. objects.dispose();
  323. vr.dispose();
  324. animation.stop();
  325. };
  326. // Events
  327. function onContextLost( event ) {
  328. event.preventDefault();
  329. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  330. _isContextLost = true;
  331. }
  332. function onContextRestore( /* event */ ) {
  333. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  334. _isContextLost = false;
  335. initGLContext();
  336. }
  337. function onMaterialDispose( event ) {
  338. var material = event.target;
  339. material.removeEventListener( 'dispose', onMaterialDispose );
  340. deallocateMaterial( material );
  341. }
  342. // Buffer deallocation
  343. function deallocateMaterial( material ) {
  344. releaseMaterialProgramReference( material );
  345. properties.remove( 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. function renderObjectImmediate( object, program ) {
  356. object.render( function ( object ) {
  357. _this.renderBufferImmediate( object, program );
  358. } );
  359. }
  360. this.renderBufferImmediate = function ( object, program ) {
  361. state.initAttributes();
  362. var buffers = properties.get( object );
  363. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  364. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  365. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  366. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  367. var programAttributes = program.getAttributes();
  368. if ( object.hasPositions ) {
  369. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  370. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  371. state.enableAttribute( programAttributes.position );
  372. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  373. }
  374. if ( object.hasNormals ) {
  375. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  376. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  377. state.enableAttribute( programAttributes.normal );
  378. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  379. }
  380. if ( object.hasUvs ) {
  381. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  382. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  383. state.enableAttribute( programAttributes.uv );
  384. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  385. }
  386. if ( object.hasColors ) {
  387. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  388. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  389. state.enableAttribute( programAttributes.color );
  390. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  391. }
  392. state.disableUnusedAttributes();
  393. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  394. object.count = 0;
  395. };
  396. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  397. var frontFaceCW = ( object.isMesh && object.normalMatrix.determinant() < 0 );
  398. state.setMaterial( material, frontFaceCW );
  399. var program = setProgram( camera, fog, material, object );
  400. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  401. var updateBuffers = false;
  402. if ( geometryProgram !== _currentGeometryProgram ) {
  403. _currentGeometryProgram = geometryProgram;
  404. updateBuffers = true;
  405. }
  406. if ( object.morphTargetInfluences ) {
  407. morphtargets.update( object, geometry, material, program );
  408. updateBuffers = true;
  409. }
  410. //
  411. var index = geometry.index;
  412. var position = geometry.attributes.position;
  413. var rangeFactor = 1;
  414. if ( material.wireframe === true ) {
  415. index = geometries.getWireframeAttribute( geometry );
  416. rangeFactor = 2;
  417. }
  418. var attribute;
  419. var renderer = bufferRenderer;
  420. if ( index !== null ) {
  421. attribute = attributes.get( index );
  422. renderer = indexedBufferRenderer;
  423. renderer.setIndex( attribute );
  424. }
  425. if ( updateBuffers ) {
  426. setupVertexAttributes( material, program, geometry );
  427. if ( index !== null ) {
  428. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  429. }
  430. }
  431. //
  432. var dataCount = Infinity;
  433. if ( index !== null ) {
  434. dataCount = index.count;
  435. } else if ( position !== undefined ) {
  436. dataCount = position.count;
  437. }
  438. var rangeStart = geometry.drawRange.start * rangeFactor;
  439. var rangeCount = geometry.drawRange.count * rangeFactor;
  440. var groupStart = group !== null ? group.start * rangeFactor : 0;
  441. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  442. var drawStart = Math.max( rangeStart, groupStart );
  443. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  444. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  445. if ( drawCount === 0 ) return;
  446. //
  447. if ( object.isMesh ) {
  448. if ( material.wireframe === true ) {
  449. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  450. renderer.setMode( _gl.LINES );
  451. } else {
  452. switch ( object.drawMode ) {
  453. case TrianglesDrawMode:
  454. renderer.setMode( _gl.TRIANGLES );
  455. break;
  456. case TriangleStripDrawMode:
  457. renderer.setMode( _gl.TRIANGLE_STRIP );
  458. break;
  459. case TriangleFanDrawMode:
  460. renderer.setMode( _gl.TRIANGLE_FAN );
  461. break;
  462. }
  463. }
  464. } else if ( object.isLine ) {
  465. var lineWidth = material.linewidth;
  466. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  467. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  468. if ( object.isLineSegments ) {
  469. renderer.setMode( _gl.LINES );
  470. } else if ( object.isLineLoop ) {
  471. renderer.setMode( _gl.LINE_LOOP );
  472. } else {
  473. renderer.setMode( _gl.LINE_STRIP );
  474. }
  475. } else if ( object.isPoints ) {
  476. renderer.setMode( _gl.POINTS );
  477. } else if ( object.isSprite ) {
  478. renderer.setMode( _gl.TRIANGLES );
  479. }
  480. if ( geometry && geometry.isInstancedBufferGeometry ) {
  481. if ( geometry.maxInstancedCount > 0 ) {
  482. renderer.renderInstances( geometry, drawStart, drawCount );
  483. }
  484. } else {
  485. renderer.render( drawStart, drawCount );
  486. }
  487. };
  488. function setupVertexAttributes( material, program, geometry ) {
  489. if ( geometry && geometry.isInstancedBufferGeometry & ! capabilities.isWebGL2 ) {
  490. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  491. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  492. return;
  493. }
  494. }
  495. state.initAttributes();
  496. var geometryAttributes = geometry.attributes;
  497. var programAttributes = program.getAttributes();
  498. var materialDefaultAttributeValues = material.defaultAttributeValues;
  499. for ( var name in programAttributes ) {
  500. var programAttribute = programAttributes[ name ];
  501. if ( programAttribute >= 0 ) {
  502. var geometryAttribute = geometryAttributes[ name ];
  503. if ( geometryAttribute !== undefined ) {
  504. var normalized = geometryAttribute.normalized;
  505. var size = geometryAttribute.itemSize;
  506. var attribute = attributes.get( geometryAttribute );
  507. // TODO Attribute may not be available on context restore
  508. if ( attribute === undefined ) continue;
  509. var buffer = attribute.buffer;
  510. var type = attribute.type;
  511. var bytesPerElement = attribute.bytesPerElement;
  512. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  513. var data = geometryAttribute.data;
  514. var stride = data.stride;
  515. var offset = geometryAttribute.offset;
  516. if ( data && data.isInstancedInterleavedBuffer ) {
  517. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  518. if ( geometry.maxInstancedCount === undefined ) {
  519. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  520. }
  521. } else {
  522. state.enableAttribute( programAttribute );
  523. }
  524. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  525. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  526. } else {
  527. if ( geometryAttribute.isInstancedBufferAttribute ) {
  528. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  529. if ( geometry.maxInstancedCount === undefined ) {
  530. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  531. }
  532. } else {
  533. state.enableAttribute( programAttribute );
  534. }
  535. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  536. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  537. }
  538. } else if ( materialDefaultAttributeValues !== undefined ) {
  539. var value = materialDefaultAttributeValues[ name ];
  540. if ( value !== undefined ) {
  541. switch ( value.length ) {
  542. case 2:
  543. _gl.vertexAttrib2fv( programAttribute, value );
  544. break;
  545. case 3:
  546. _gl.vertexAttrib3fv( programAttribute, value );
  547. break;
  548. case 4:
  549. _gl.vertexAttrib4fv( programAttribute, value );
  550. break;
  551. default:
  552. _gl.vertexAttrib1fv( programAttribute, value );
  553. }
  554. }
  555. }
  556. }
  557. }
  558. state.disableUnusedAttributes();
  559. }
  560. // Compile
  561. this.compile = function ( scene, camera ) {
  562. currentRenderState = renderStates.get( scene, camera );
  563. currentRenderState.init();
  564. scene.traverse( function ( object ) {
  565. if ( object.isLight ) {
  566. currentRenderState.pushLight( object );
  567. if ( object.castShadow ) {
  568. currentRenderState.pushShadow( object );
  569. }
  570. }
  571. } );
  572. currentRenderState.setupLights( camera );
  573. scene.traverse( function ( object ) {
  574. if ( object.material ) {
  575. if ( Array.isArray( object.material ) ) {
  576. for ( var i = 0; i < object.material.length; i ++ ) {
  577. initMaterial( object.material[ i ], scene.fog, object );
  578. }
  579. } else {
  580. initMaterial( object.material, scene.fog, object );
  581. }
  582. }
  583. } );
  584. };
  585. // Animation Loop
  586. var onAnimationFrameCallback = null;
  587. function onAnimationFrame( time ) {
  588. if ( vr.isPresenting() ) return;
  589. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  590. }
  591. var animation = new WebGLAnimation();
  592. animation.setAnimationLoop( onAnimationFrame );
  593. if ( typeof window !== 'undefined' ) animation.setContext( window );
  594. this.setAnimationLoop = function ( callback ) {
  595. onAnimationFrameCallback = callback;
  596. vr.setAnimationLoop( callback );
  597. animation.start();
  598. };
  599. // Rendering
  600. this.render = function ( scene, camera, renderTarget, forceClear ) {
  601. if ( ! ( camera && camera.isCamera ) ) {
  602. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  603. return;
  604. }
  605. if ( _isContextLost ) return;
  606. // reset caching for this frame
  607. _currentGeometryProgram = '';
  608. _currentMaterialId = - 1;
  609. _currentCamera = null;
  610. // update scene graph
  611. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  612. // update camera matrices and frustum
  613. if ( camera.parent === null ) camera.updateMatrixWorld();
  614. if ( vr.enabled ) {
  615. camera = vr.getCamera( camera );
  616. }
  617. //
  618. currentRenderState = renderStates.get( scene, camera );
  619. currentRenderState.init();
  620. scene.onBeforeRender( _this, scene, camera, renderTarget );
  621. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  622. _frustum.setFromMatrix( _projScreenMatrix );
  623. _localClippingEnabled = this.localClippingEnabled;
  624. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  625. currentRenderList = renderLists.get( scene, camera );
  626. currentRenderList.init();
  627. projectObject( scene, camera, _this.sortObjects );
  628. if ( _this.sortObjects === true ) {
  629. currentRenderList.sort();
  630. }
  631. //
  632. if ( _clippingEnabled ) _clipping.beginShadows();
  633. var shadowsArray = currentRenderState.state.shadowsArray;
  634. shadowMap.render( shadowsArray, scene, camera );
  635. currentRenderState.setupLights( camera );
  636. if ( _clippingEnabled ) _clipping.endShadows();
  637. //
  638. if ( this.info.autoReset ) this.info.reset();
  639. if ( renderTarget === undefined ) {
  640. renderTarget = null;
  641. }
  642. this.setRenderTarget( renderTarget );
  643. //
  644. background.render( currentRenderList, scene, camera, forceClear );
  645. // render scene
  646. var opaqueObjects = currentRenderList.opaque;
  647. var transparentObjects = currentRenderList.transparent;
  648. var spriteObjects = currentRenderList.sprites;
  649. if ( scene.overrideMaterial ) {
  650. var overrideMaterial = scene.overrideMaterial;
  651. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  652. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  653. if ( spriteObjects.length ) renderObjects( spriteObjects, scene, camera, overrideMaterial );
  654. } else {
  655. // opaque pass (front-to-back order)
  656. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  657. // transparent pass (back-to-front order)
  658. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  659. //
  660. if ( spriteObjects.length ) renderObjects( spriteObjects, scene, camera );
  661. }
  662. // Generate mipmap if we're using any kind of mipmap filtering
  663. if ( renderTarget ) {
  664. textures.updateRenderTargetMipmap( renderTarget );
  665. }
  666. // Ensure depth buffer writing is enabled so it can be cleared on next render
  667. state.buffers.depth.setTest( true );
  668. state.buffers.depth.setMask( true );
  669. state.buffers.color.setMask( true );
  670. state.setPolygonOffset( false );
  671. scene.onAfterRender( _this, scene, camera );
  672. if ( vr.enabled ) {
  673. vr.submitFrame();
  674. }
  675. // _gl.finish();
  676. currentRenderList = null;
  677. currentRenderState = null;
  678. };
  679. /*
  680. // TODO Duplicated code (Frustum)
  681. var _sphere = new Sphere();
  682. function isObjectViewable( object ) {
  683. var geometry = object.geometry;
  684. if ( geometry.boundingSphere === null )
  685. geometry.computeBoundingSphere();
  686. _sphere.copy( geometry.boundingSphere ).
  687. applyMatrix4( object.matrixWorld );
  688. return isSphereViewable( _sphere );
  689. }
  690. function isSpriteViewable( sprite ) {
  691. _sphere.center.set( 0, 0, 0 );
  692. _sphere.radius = 0.7071067811865476;
  693. _sphere.applyMatrix4( sprite.matrixWorld );
  694. return isSphereViewable( _sphere );
  695. }
  696. function isSphereViewable( sphere ) {
  697. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  698. var numPlanes = _clipping.numPlanes;
  699. if ( numPlanes === 0 ) return true;
  700. var planes = _this.clippingPlanes,
  701. center = sphere.center,
  702. negRad = - sphere.radius,
  703. i = 0;
  704. do {
  705. // out when deeper than radius in the negative halfspace
  706. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  707. } while ( ++ i !== numPlanes );
  708. return true;
  709. }
  710. */
  711. function projectObject( object, camera, sortObjects ) {
  712. if ( object.visible === false ) return;
  713. var visible = object.layers.test( camera.layers );
  714. if ( visible ) {
  715. if ( object.isLight ) {
  716. currentRenderState.pushLight( object );
  717. if ( object.castShadow ) {
  718. currentRenderState.pushShadow( object );
  719. }
  720. } else if ( object.isSprite ) {
  721. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  722. if ( sortObjects ) {
  723. _vector3.setFromMatrixPosition( object.matrixWorld )
  724. .applyMatrix4( _projScreenMatrix );
  725. }
  726. var geometry = objects.update( object );
  727. var material = object.material;
  728. currentRenderList.push( object, geometry, material, _vector3.z, null );
  729. }
  730. } else if ( object.isImmediateRenderObject ) {
  731. if ( sortObjects ) {
  732. _vector3.setFromMatrixPosition( object.matrixWorld )
  733. .applyMatrix4( _projScreenMatrix );
  734. }
  735. currentRenderList.push( object, null, object.material, _vector3.z, null );
  736. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  737. if ( object.isSkinnedMesh ) {
  738. object.skeleton.update();
  739. }
  740. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  741. if ( sortObjects ) {
  742. _vector3.setFromMatrixPosition( object.matrixWorld )
  743. .applyMatrix4( _projScreenMatrix );
  744. }
  745. var geometry = objects.update( object );
  746. var material = object.material;
  747. if ( Array.isArray( material ) ) {
  748. var groups = geometry.groups;
  749. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  750. var group = groups[ i ];
  751. var groupMaterial = material[ group.materialIndex ];
  752. if ( groupMaterial && groupMaterial.visible ) {
  753. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  754. }
  755. }
  756. } else if ( material.visible ) {
  757. currentRenderList.push( object, geometry, material, _vector3.z, null );
  758. }
  759. }
  760. }
  761. }
  762. var children = object.children;
  763. for ( var i = 0, l = children.length; i < l; i ++ ) {
  764. projectObject( children[ i ], camera, sortObjects );
  765. }
  766. }
  767. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  768. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  769. var renderItem = renderList[ i ];
  770. var object = renderItem.object;
  771. var geometry = renderItem.geometry;
  772. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  773. var group = renderItem.group;
  774. if ( camera.isArrayCamera ) {
  775. _currentArrayCamera = camera;
  776. var cameras = camera.cameras;
  777. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  778. var camera2 = cameras[ j ];
  779. if ( object.layers.test( camera2.layers ) ) {
  780. if ( 'viewport' in camera2 ) { // XR
  781. state.viewport( _currentViewport.copy( camera2.viewport ) );
  782. } else {
  783. var bounds = camera2.bounds;
  784. var x = bounds.x * _width;
  785. var y = bounds.y * _height;
  786. var width = bounds.z * _width;
  787. var height = bounds.w * _height;
  788. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  789. }
  790. renderObject( object, scene, camera2, geometry, material, group );
  791. }
  792. }
  793. } else {
  794. _currentArrayCamera = null;
  795. renderObject( object, scene, camera, geometry, material, group );
  796. }
  797. }
  798. }
  799. function renderObject( object, scene, camera, geometry, material, group ) {
  800. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  801. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  802. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  803. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  804. if ( object.isImmediateRenderObject ) {
  805. state.setMaterial( material );
  806. var program = setProgram( camera, scene.fog, material, object );
  807. _currentGeometryProgram = '';
  808. renderObjectImmediate( object, program );
  809. } else {
  810. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  811. }
  812. object.onAfterRender( _this, scene, camera, geometry, material, group );
  813. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  814. }
  815. function initMaterial( material, fog, object ) {
  816. var materialProperties = properties.get( material );
  817. var lights = currentRenderState.state.lights;
  818. var shadowsArray = currentRenderState.state.shadowsArray;
  819. var parameters = programCache.getParameters(
  820. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  821. var code = programCache.getProgramCode( material, parameters );
  822. var program = materialProperties.program;
  823. var programChange = true;
  824. if ( program === undefined ) {
  825. // new material
  826. material.addEventListener( 'dispose', onMaterialDispose );
  827. } else if ( program.code !== code ) {
  828. // changed glsl or parameters
  829. releaseMaterialProgramReference( material );
  830. } else if ( materialProperties.lightsHash !== lights.state.hash ) {
  831. properties.update( material, 'lightsHash', lights.state.hash );
  832. programChange = false;
  833. } else if ( parameters.shaderID !== undefined ) {
  834. // same glsl and uniform list
  835. return;
  836. } else {
  837. // only rebuild uniform list
  838. programChange = false;
  839. }
  840. if ( programChange ) {
  841. if ( parameters.shaderID ) {
  842. var shader = ShaderLib[ parameters.shaderID ];
  843. materialProperties.shader = {
  844. name: material.type,
  845. uniforms: UniformsUtils.clone( shader.uniforms ),
  846. vertexShader: shader.vertexShader,
  847. fragmentShader: shader.fragmentShader
  848. };
  849. } else {
  850. materialProperties.shader = {
  851. name: material.type,
  852. uniforms: material.uniforms,
  853. vertexShader: material.vertexShader,
  854. fragmentShader: material.fragmentShader
  855. };
  856. }
  857. material.onBeforeCompile( materialProperties.shader, _this );
  858. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  859. materialProperties.program = program;
  860. material.program = program;
  861. }
  862. var programAttributes = program.getAttributes();
  863. if ( material.morphTargets ) {
  864. material.numSupportedMorphTargets = 0;
  865. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  866. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  867. material.numSupportedMorphTargets ++;
  868. }
  869. }
  870. }
  871. if ( material.morphNormals ) {
  872. material.numSupportedMorphNormals = 0;
  873. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  874. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  875. material.numSupportedMorphNormals ++;
  876. }
  877. }
  878. }
  879. var uniforms = materialProperties.shader.uniforms;
  880. if ( ! material.isShaderMaterial &&
  881. ! material.isRawShaderMaterial ||
  882. material.clipping === true ) {
  883. materialProperties.numClippingPlanes = _clipping.numPlanes;
  884. materialProperties.numIntersection = _clipping.numIntersection;
  885. uniforms.clippingPlanes = _clipping.uniform;
  886. }
  887. materialProperties.fog = fog;
  888. // store the light setup it was created for
  889. materialProperties.lightsHash = lights.state.hash;
  890. if ( material.lights ) {
  891. // wire up the material to this renderer's lighting state
  892. uniforms.ambientLightColor.value = lights.state.ambient;
  893. uniforms.directionalLights.value = lights.state.directional;
  894. uniforms.spotLights.value = lights.state.spot;
  895. uniforms.rectAreaLights.value = lights.state.rectArea;
  896. uniforms.pointLights.value = lights.state.point;
  897. uniforms.hemisphereLights.value = lights.state.hemi;
  898. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  899. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  900. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  901. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  902. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  903. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  904. // TODO (abelnation): add area lights shadow info to uniforms
  905. }
  906. var progUniforms = materialProperties.program.getUniforms(),
  907. uniformsList =
  908. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  909. materialProperties.uniformsList = uniformsList;
  910. }
  911. function setProgram( camera, fog, material, object ) {
  912. _usedTextureUnits = 0;
  913. var materialProperties = properties.get( material );
  914. var lights = currentRenderState.state.lights;
  915. if ( _clippingEnabled ) {
  916. if ( _localClippingEnabled || camera !== _currentCamera ) {
  917. var useCache =
  918. camera === _currentCamera &&
  919. material.id === _currentMaterialId;
  920. // we might want to call this function with some ClippingGroup
  921. // object instead of the material, once it becomes feasible
  922. // (#8465, #8379)
  923. _clipping.setState(
  924. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  925. camera, materialProperties, useCache );
  926. }
  927. }
  928. if ( material.needsUpdate === false ) {
  929. if ( materialProperties.program === undefined ) {
  930. material.needsUpdate = true;
  931. } else if ( material.fog && materialProperties.fog !== fog ) {
  932. material.needsUpdate = true;
  933. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  934. material.needsUpdate = true;
  935. } else if ( materialProperties.numClippingPlanes !== undefined &&
  936. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  937. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  938. material.needsUpdate = true;
  939. }
  940. }
  941. if ( material.needsUpdate ) {
  942. initMaterial( material, fog, object );
  943. material.needsUpdate = false;
  944. }
  945. var refreshProgram = false;
  946. var refreshMaterial = false;
  947. var refreshLights = false;
  948. var program = materialProperties.program,
  949. p_uniforms = program.getUniforms(),
  950. m_uniforms = materialProperties.shader.uniforms;
  951. if ( state.useProgram( program.program ) ) {
  952. refreshProgram = true;
  953. refreshMaterial = true;
  954. refreshLights = true;
  955. }
  956. if ( material.id !== _currentMaterialId ) {
  957. _currentMaterialId = material.id;
  958. refreshMaterial = true;
  959. }
  960. if ( refreshProgram || camera !== _currentCamera ) {
  961. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  962. if ( capabilities.logarithmicDepthBuffer ) {
  963. p_uniforms.setValue( _gl, 'logDepthBufFC',
  964. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  965. }
  966. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  967. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  968. _currentCamera = ( _currentArrayCamera || camera );
  969. // lighting uniforms depend on the camera so enforce an update
  970. // now, in case this material supports lights - or later, when
  971. // the next material that does gets activated:
  972. refreshMaterial = true; // set to true on material change
  973. refreshLights = true; // remains set until update done
  974. }
  975. // load material specific uniforms
  976. // (shader material also gets them for the sake of genericity)
  977. if ( material.isShaderMaterial ||
  978. material.isMeshPhongMaterial ||
  979. material.isMeshStandardMaterial ||
  980. material.envMap ) {
  981. var uCamPos = p_uniforms.map.cameraPosition;
  982. if ( uCamPos !== undefined ) {
  983. uCamPos.setValue( _gl,
  984. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  985. }
  986. }
  987. if ( material.isMeshPhongMaterial ||
  988. material.isMeshLambertMaterial ||
  989. material.isMeshBasicMaterial ||
  990. material.isMeshStandardMaterial ||
  991. material.isShaderMaterial ||
  992. material.skinning ) {
  993. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  994. }
  995. }
  996. // skinning uniforms must be set even if material didn't change
  997. // auto-setting of texture unit for bone texture must go before other textures
  998. // not sure why, but otherwise weird things happen
  999. if ( material.skinning ) {
  1000. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1001. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1002. var skeleton = object.skeleton;
  1003. if ( skeleton ) {
  1004. var bones = skeleton.bones;
  1005. if ( capabilities.floatVertexTextures ) {
  1006. if ( skeleton.boneTexture === undefined ) {
  1007. // layout (1 matrix = 4 pixels)
  1008. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  1009. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  1010. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  1011. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  1012. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  1013. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  1014. size = _Math.ceilPowerOfTwo( size );
  1015. size = Math.max( size, 4 );
  1016. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  1017. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  1018. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  1019. boneTexture.needsUpdate = true;
  1020. skeleton.boneMatrices = boneMatrices;
  1021. skeleton.boneTexture = boneTexture;
  1022. skeleton.boneTextureSize = size;
  1023. }
  1024. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  1025. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  1026. } else {
  1027. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1028. }
  1029. }
  1030. }
  1031. if ( refreshMaterial ) {
  1032. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1033. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  1034. if ( material.lights ) {
  1035. // the current material requires lighting info
  1036. // note: all lighting uniforms are always set correctly
  1037. // they simply reference the renderer's state for their
  1038. // values
  1039. //
  1040. // use the current material's .needsUpdate flags to set
  1041. // the GL state when required
  1042. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1043. }
  1044. // refresh uniforms common to several materials
  1045. if ( fog && material.fog ) {
  1046. refreshUniformsFog( m_uniforms, fog );
  1047. }
  1048. if ( material.isMeshBasicMaterial ) {
  1049. refreshUniformsCommon( m_uniforms, material );
  1050. } else if ( material.isMeshLambertMaterial ) {
  1051. refreshUniformsCommon( m_uniforms, material );
  1052. refreshUniformsLambert( m_uniforms, material );
  1053. } else if ( material.isMeshPhongMaterial ) {
  1054. refreshUniformsCommon( m_uniforms, material );
  1055. if ( material.isMeshToonMaterial ) {
  1056. refreshUniformsToon( m_uniforms, material );
  1057. } else {
  1058. refreshUniformsPhong( m_uniforms, material );
  1059. }
  1060. } else if ( material.isMeshStandardMaterial ) {
  1061. refreshUniformsCommon( m_uniforms, material );
  1062. if ( material.isMeshPhysicalMaterial ) {
  1063. refreshUniformsPhysical( m_uniforms, material );
  1064. } else {
  1065. refreshUniformsStandard( m_uniforms, material );
  1066. }
  1067. } else if ( material.isMeshDepthMaterial ) {
  1068. refreshUniformsCommon( m_uniforms, material );
  1069. refreshUniformsDepth( m_uniforms, material );
  1070. } else if ( material.isMeshDistanceMaterial ) {
  1071. refreshUniformsCommon( m_uniforms, material );
  1072. refreshUniformsDistance( m_uniforms, material );
  1073. } else if ( material.isMeshNormalMaterial ) {
  1074. refreshUniformsCommon( m_uniforms, material );
  1075. refreshUniformsNormal( m_uniforms, material );
  1076. } else if ( material.isLineBasicMaterial ) {
  1077. refreshUniformsLine( m_uniforms, material );
  1078. if ( material.isLineDashedMaterial ) {
  1079. refreshUniformsDash( m_uniforms, material );
  1080. }
  1081. } else if ( material.isPointsMaterial ) {
  1082. refreshUniformsPoints( m_uniforms, material );
  1083. } else if ( material.isSpriteMaterial ) {
  1084. refreshUniformsSprites( m_uniforms, material );
  1085. } else if ( material.isShadowMaterial ) {
  1086. m_uniforms.color.value = material.color;
  1087. m_uniforms.opacity.value = material.opacity;
  1088. }
  1089. // RectAreaLight Texture
  1090. // TODO (mrdoob): Find a nicer implementation
  1091. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  1092. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  1093. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  1094. }
  1095. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1096. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  1097. material.uniformsNeedUpdate = false;
  1098. }
  1099. if ( material.isSpriteMaterial ) {
  1100. p_uniforms.setValue( _gl, 'center', object.center );
  1101. }
  1102. // common matrices
  1103. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1104. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1105. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1106. return program;
  1107. }
  1108. // Uniforms (refresh uniforms objects)
  1109. function refreshUniformsCommon( uniforms, material ) {
  1110. uniforms.opacity.value = material.opacity;
  1111. if ( material.color ) {
  1112. uniforms.diffuse.value = material.color;
  1113. }
  1114. if ( material.emissive ) {
  1115. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1116. }
  1117. if ( material.map ) {
  1118. uniforms.map.value = material.map;
  1119. }
  1120. if ( material.alphaMap ) {
  1121. uniforms.alphaMap.value = material.alphaMap;
  1122. }
  1123. if ( material.specularMap ) {
  1124. uniforms.specularMap.value = material.specularMap;
  1125. }
  1126. if ( material.envMap ) {
  1127. uniforms.envMap.value = material.envMap;
  1128. // don't flip CubeTexture envMaps, flip everything else:
  1129. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1130. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1131. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1132. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  1133. uniforms.reflectivity.value = material.reflectivity;
  1134. uniforms.refractionRatio.value = material.refractionRatio;
  1135. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  1136. }
  1137. if ( material.lightMap ) {
  1138. uniforms.lightMap.value = material.lightMap;
  1139. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1140. }
  1141. if ( material.aoMap ) {
  1142. uniforms.aoMap.value = material.aoMap;
  1143. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1144. }
  1145. // uv repeat and offset setting priorities
  1146. // 1. color map
  1147. // 2. specular map
  1148. // 3. normal map
  1149. // 4. bump map
  1150. // 5. alpha map
  1151. // 6. emissive map
  1152. var uvScaleMap;
  1153. if ( material.map ) {
  1154. uvScaleMap = material.map;
  1155. } else if ( material.specularMap ) {
  1156. uvScaleMap = material.specularMap;
  1157. } else if ( material.displacementMap ) {
  1158. uvScaleMap = material.displacementMap;
  1159. } else if ( material.normalMap ) {
  1160. uvScaleMap = material.normalMap;
  1161. } else if ( material.bumpMap ) {
  1162. uvScaleMap = material.bumpMap;
  1163. } else if ( material.roughnessMap ) {
  1164. uvScaleMap = material.roughnessMap;
  1165. } else if ( material.metalnessMap ) {
  1166. uvScaleMap = material.metalnessMap;
  1167. } else if ( material.alphaMap ) {
  1168. uvScaleMap = material.alphaMap;
  1169. } else if ( material.emissiveMap ) {
  1170. uvScaleMap = material.emissiveMap;
  1171. }
  1172. if ( uvScaleMap !== undefined ) {
  1173. // backwards compatibility
  1174. if ( uvScaleMap.isWebGLRenderTarget ) {
  1175. uvScaleMap = uvScaleMap.texture;
  1176. }
  1177. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1178. uvScaleMap.updateMatrix();
  1179. }
  1180. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1181. }
  1182. }
  1183. function refreshUniformsLine( uniforms, material ) {
  1184. uniforms.diffuse.value = material.color;
  1185. uniforms.opacity.value = material.opacity;
  1186. }
  1187. function refreshUniformsDash( uniforms, material ) {
  1188. uniforms.dashSize.value = material.dashSize;
  1189. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1190. uniforms.scale.value = material.scale;
  1191. }
  1192. function refreshUniformsPoints( uniforms, material ) {
  1193. uniforms.diffuse.value = material.color;
  1194. uniforms.opacity.value = material.opacity;
  1195. uniforms.size.value = material.size * _pixelRatio;
  1196. uniforms.scale.value = _height * 0.5;
  1197. uniforms.map.value = material.map;
  1198. if ( material.map !== null ) {
  1199. if ( material.map.matrixAutoUpdate === true ) {
  1200. material.map.updateMatrix();
  1201. }
  1202. uniforms.uvTransform.value.copy( material.map.matrix );
  1203. }
  1204. }
  1205. function refreshUniformsSprites( uniforms, material ) {
  1206. uniforms.diffuse.value = material.color;
  1207. uniforms.opacity.value = material.opacity;
  1208. uniforms.rotation.value = material.rotation;
  1209. uniforms.map.value = material.map;
  1210. if ( material.map !== null ) {
  1211. if ( material.map.matrixAutoUpdate === true ) {
  1212. material.map.updateMatrix();
  1213. }
  1214. uniforms.uvTransform.value.copy( material.map.matrix );
  1215. }
  1216. }
  1217. function refreshUniformsFog( uniforms, fog ) {
  1218. uniforms.fogColor.value = fog.color;
  1219. if ( fog.isFog ) {
  1220. uniforms.fogNear.value = fog.near;
  1221. uniforms.fogFar.value = fog.far;
  1222. } else if ( fog.isFogExp2 ) {
  1223. uniforms.fogDensity.value = fog.density;
  1224. }
  1225. }
  1226. function refreshUniformsLambert( uniforms, material ) {
  1227. if ( material.emissiveMap ) {
  1228. uniforms.emissiveMap.value = material.emissiveMap;
  1229. }
  1230. }
  1231. function refreshUniformsPhong( uniforms, material ) {
  1232. uniforms.specular.value = material.specular;
  1233. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1234. if ( material.emissiveMap ) {
  1235. uniforms.emissiveMap.value = material.emissiveMap;
  1236. }
  1237. if ( material.bumpMap ) {
  1238. uniforms.bumpMap.value = material.bumpMap;
  1239. uniforms.bumpScale.value = material.bumpScale;
  1240. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1241. }
  1242. if ( material.normalMap ) {
  1243. uniforms.normalMap.value = material.normalMap;
  1244. uniforms.normalScale.value.copy( material.normalScale );
  1245. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1246. }
  1247. if ( material.displacementMap ) {
  1248. uniforms.displacementMap.value = material.displacementMap;
  1249. uniforms.displacementScale.value = material.displacementScale;
  1250. uniforms.displacementBias.value = material.displacementBias;
  1251. }
  1252. }
  1253. function refreshUniformsToon( uniforms, material ) {
  1254. refreshUniformsPhong( uniforms, material );
  1255. if ( material.gradientMap ) {
  1256. uniforms.gradientMap.value = material.gradientMap;
  1257. }
  1258. }
  1259. function refreshUniformsStandard( uniforms, material ) {
  1260. uniforms.roughness.value = material.roughness;
  1261. uniforms.metalness.value = material.metalness;
  1262. if ( material.roughnessMap ) {
  1263. uniforms.roughnessMap.value = material.roughnessMap;
  1264. }
  1265. if ( material.metalnessMap ) {
  1266. uniforms.metalnessMap.value = material.metalnessMap;
  1267. }
  1268. if ( material.emissiveMap ) {
  1269. uniforms.emissiveMap.value = material.emissiveMap;
  1270. }
  1271. if ( material.bumpMap ) {
  1272. uniforms.bumpMap.value = material.bumpMap;
  1273. uniforms.bumpScale.value = material.bumpScale;
  1274. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1275. }
  1276. if ( material.normalMap ) {
  1277. uniforms.normalMap.value = material.normalMap;
  1278. uniforms.normalScale.value.copy( material.normalScale );
  1279. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1280. }
  1281. if ( material.displacementMap ) {
  1282. uniforms.displacementMap.value = material.displacementMap;
  1283. uniforms.displacementScale.value = material.displacementScale;
  1284. uniforms.displacementBias.value = material.displacementBias;
  1285. }
  1286. if ( material.envMap ) {
  1287. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1288. uniforms.envMapIntensity.value = material.envMapIntensity;
  1289. }
  1290. }
  1291. function refreshUniformsPhysical( uniforms, material ) {
  1292. refreshUniformsStandard( uniforms, material );
  1293. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  1294. uniforms.clearCoat.value = material.clearCoat;
  1295. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1296. }
  1297. function refreshUniformsDepth( uniforms, material ) {
  1298. if ( material.displacementMap ) {
  1299. uniforms.displacementMap.value = material.displacementMap;
  1300. uniforms.displacementScale.value = material.displacementScale;
  1301. uniforms.displacementBias.value = material.displacementBias;
  1302. }
  1303. }
  1304. function refreshUniformsDistance( uniforms, material ) {
  1305. if ( material.displacementMap ) {
  1306. uniforms.displacementMap.value = material.displacementMap;
  1307. uniforms.displacementScale.value = material.displacementScale;
  1308. uniforms.displacementBias.value = material.displacementBias;
  1309. }
  1310. uniforms.referencePosition.value.copy( material.referencePosition );
  1311. uniforms.nearDistance.value = material.nearDistance;
  1312. uniforms.farDistance.value = material.farDistance;
  1313. }
  1314. function refreshUniformsNormal( uniforms, material ) {
  1315. if ( material.bumpMap ) {
  1316. uniforms.bumpMap.value = material.bumpMap;
  1317. uniforms.bumpScale.value = material.bumpScale;
  1318. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1319. }
  1320. if ( material.normalMap ) {
  1321. uniforms.normalMap.value = material.normalMap;
  1322. uniforms.normalScale.value.copy( material.normalScale );
  1323. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1324. }
  1325. if ( material.displacementMap ) {
  1326. uniforms.displacementMap.value = material.displacementMap;
  1327. uniforms.displacementScale.value = material.displacementScale;
  1328. uniforms.displacementBias.value = material.displacementBias;
  1329. }
  1330. }
  1331. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1332. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1333. uniforms.ambientLightColor.needsUpdate = value;
  1334. uniforms.directionalLights.needsUpdate = value;
  1335. uniforms.pointLights.needsUpdate = value;
  1336. uniforms.spotLights.needsUpdate = value;
  1337. uniforms.rectAreaLights.needsUpdate = value;
  1338. uniforms.hemisphereLights.needsUpdate = value;
  1339. }
  1340. // Textures
  1341. function allocTextureUnit() {
  1342. var textureUnit = _usedTextureUnits;
  1343. if ( textureUnit >= capabilities.maxTextures ) {
  1344. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1345. }
  1346. _usedTextureUnits += 1;
  1347. return textureUnit;
  1348. }
  1349. this.allocTextureUnit = allocTextureUnit;
  1350. // this.setTexture2D = setTexture2D;
  1351. this.setTexture2D = ( function () {
  1352. var warned = false;
  1353. // backwards compatibility: peel texture.texture
  1354. return function setTexture2D( texture, slot ) {
  1355. if ( texture && texture.isWebGLRenderTarget ) {
  1356. if ( ! warned ) {
  1357. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1358. warned = true;
  1359. }
  1360. texture = texture.texture;
  1361. }
  1362. textures.setTexture2D( texture, slot );
  1363. };
  1364. }() );
  1365. this.setTexture = ( function () {
  1366. var warned = false;
  1367. return function setTexture( texture, slot ) {
  1368. if ( ! warned ) {
  1369. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1370. warned = true;
  1371. }
  1372. textures.setTexture2D( texture, slot );
  1373. };
  1374. }() );
  1375. this.setTextureCube = ( function () {
  1376. var warned = false;
  1377. return function setTextureCube( texture, slot ) {
  1378. // backwards compatibility: peel texture.texture
  1379. if ( texture && texture.isWebGLRenderTargetCube ) {
  1380. if ( ! warned ) {
  1381. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1382. warned = true;
  1383. }
  1384. texture = texture.texture;
  1385. }
  1386. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1387. // TODO: unify these code paths
  1388. if ( ( texture && texture.isCubeTexture ) ||
  1389. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1390. // CompressedTexture can have Array in image :/
  1391. // this function alone should take care of cube textures
  1392. textures.setTextureCube( texture, slot );
  1393. } else {
  1394. // assumed: texture property of THREE.WebGLRenderTargetCube
  1395. textures.setTextureCubeDynamic( texture, slot );
  1396. }
  1397. };
  1398. }() );
  1399. //
  1400. this.setFramebuffer = function ( value ) {
  1401. _framebuffer = value;
  1402. };
  1403. this.getRenderTarget = function () {
  1404. return _currentRenderTarget;
  1405. };
  1406. this.setRenderTarget = function ( renderTarget ) {
  1407. _currentRenderTarget = renderTarget;
  1408. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1409. textures.setupRenderTarget( renderTarget );
  1410. }
  1411. var framebuffer = _framebuffer;
  1412. var isCube = false;
  1413. if ( renderTarget ) {
  1414. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1415. if ( renderTarget.isWebGLRenderTargetCube ) {
  1416. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  1417. isCube = true;
  1418. } else {
  1419. framebuffer = __webglFramebuffer;
  1420. }
  1421. _currentViewport.copy( renderTarget.viewport );
  1422. _currentScissor.copy( renderTarget.scissor );
  1423. _currentScissorTest = renderTarget.scissorTest;
  1424. } else {
  1425. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1426. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1427. _currentScissorTest = _scissorTest;
  1428. }
  1429. if ( _currentFramebuffer !== framebuffer ) {
  1430. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1431. _currentFramebuffer = framebuffer;
  1432. }
  1433. state.viewport( _currentViewport );
  1434. state.scissor( _currentScissor );
  1435. state.setScissorTest( _currentScissorTest );
  1436. if ( isCube ) {
  1437. var textureProperties = properties.get( renderTarget.texture );
  1438. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1439. }
  1440. };
  1441. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1442. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1443. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1444. return;
  1445. }
  1446. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1447. if ( framebuffer ) {
  1448. var restore = false;
  1449. if ( framebuffer !== _currentFramebuffer ) {
  1450. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1451. restore = true;
  1452. }
  1453. try {
  1454. var texture = renderTarget.texture;
  1455. var textureFormat = texture.format;
  1456. var textureType = texture.type;
  1457. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1458. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1459. return;
  1460. }
  1461. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1462. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1463. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  1464. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1465. return;
  1466. }
  1467. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1468. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1469. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1470. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1471. }
  1472. } else {
  1473. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1474. }
  1475. } finally {
  1476. if ( restore ) {
  1477. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1478. }
  1479. }
  1480. }
  1481. };
  1482. this.copyFramebufferToTexture = function ( position, texture, level ) {
  1483. var width = texture.image.width;
  1484. var height = texture.image.height;
  1485. var glFormat = utils.convert( texture.format );
  1486. this.setTexture2D( texture, 0 );
  1487. _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 );
  1488. };
  1489. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  1490. var width = srcTexture.image.width;
  1491. var height = srcTexture.image.height;
  1492. var glFormat = utils.convert( dstTexture.format );
  1493. var glType = utils.convert( dstTexture.type );
  1494. this.setTexture2D( dstTexture, 0 );
  1495. if ( srcTexture.isDataTexture ) {
  1496. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  1497. } else {
  1498. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  1499. }
  1500. };
  1501. }
  1502. export { WebGLRenderer };