WebGLRenderer.js 58 KB

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