WebGLRenderer.js 65 KB

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