WebGLRenderer.js 64 KB

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