WebGLRenderer.js 60 KB

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