WebGLRenderer.js 61 KB

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