WebGLRenderer.js 61 KB

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