WebGLRenderer.js 61 KB

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