WebGLRenderer.js 66 KB

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