WebGLRenderer.js 66 KB

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