WebGLRenderer.js 62 KB

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