WebGLRenderer.js 59 KB

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