WebGLRenderer.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618
  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. refreshUniformsCommon( m_uniforms, material );
  1035. } else if ( material.isMeshLambertMaterial ) {
  1036. refreshUniformsCommon( m_uniforms, material );
  1037. refreshUniformsLambert( m_uniforms, material );
  1038. } else if ( material.isMeshPhongMaterial ) {
  1039. refreshUniformsCommon( m_uniforms, material );
  1040. if ( material.isMeshToonMaterial ) {
  1041. refreshUniformsToon( m_uniforms, material );
  1042. } else {
  1043. refreshUniformsPhong( m_uniforms, material );
  1044. }
  1045. } else if ( material.isMeshStandardMaterial ) {
  1046. refreshUniformsCommon( m_uniforms, material );
  1047. if ( material.isMeshPhysicalMaterial ) {
  1048. refreshUniformsPhysical( m_uniforms, material );
  1049. } else {
  1050. refreshUniformsStandard( m_uniforms, material );
  1051. }
  1052. } else if ( material.isMeshNormalMaterial ) {
  1053. refreshUniformsCommon( m_uniforms, material );
  1054. } else if ( material.isMeshDepthMaterial ) {
  1055. refreshUniformsCommon( m_uniforms, material );
  1056. refreshUniformsDepth( m_uniforms, material );
  1057. } else if ( material.isMeshDistanceMaterial ) {
  1058. refreshUniformsCommon( m_uniforms, material );
  1059. refreshUniformsDistance( m_uniforms, material );
  1060. } else if ( material.isMeshNormalMaterial ) {
  1061. refreshUniformsNormal( m_uniforms, material );
  1062. } else if ( material.isLineBasicMaterial ) {
  1063. refreshUniformsLine( m_uniforms, material );
  1064. if ( material.isLineDashedMaterial ) {
  1065. refreshUniformsDash( m_uniforms, material );
  1066. }
  1067. } else if ( material.isPointsMaterial ) {
  1068. refreshUniformsPoints( m_uniforms, material );
  1069. } else if ( material.isShadowMaterial ) {
  1070. m_uniforms.color.value = material.color;
  1071. m_uniforms.opacity.value = material.opacity;
  1072. }
  1073. // RectAreaLight Texture
  1074. // TODO (mrdoob): Find a nicer implementation
  1075. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  1076. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  1077. WebGLUniforms.upload(
  1078. _gl, materialProperties.uniformsList, m_uniforms, _this );
  1079. }
  1080. // common matrices
  1081. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1082. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1083. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1084. return program;
  1085. }
  1086. // Uniforms (refresh uniforms objects)
  1087. function refreshUniformsCommon( uniforms, material ) {
  1088. uniforms.opacity.value = material.opacity;
  1089. if ( material.color ) {
  1090. uniforms.diffuse.value = material.color;
  1091. }
  1092. if ( material.emissive ) {
  1093. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1094. }
  1095. if ( material.map ) {
  1096. uniforms.map.value = material.map;
  1097. }
  1098. if ( material.alphaMap ) {
  1099. uniforms.alphaMap.value = material.alphaMap;
  1100. }
  1101. if ( material.specularMap ) {
  1102. uniforms.specularMap.value = material.specularMap;
  1103. }
  1104. if ( material.envMap ) {
  1105. uniforms.envMap.value = material.envMap;
  1106. // don't flip CubeTexture envMaps, flip everything else:
  1107. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1108. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1109. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1110. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  1111. uniforms.reflectivity.value = material.reflectivity;
  1112. uniforms.refractionRatio.value = material.refractionRatio;
  1113. }
  1114. if ( material.lightMap ) {
  1115. uniforms.lightMap.value = material.lightMap;
  1116. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1117. }
  1118. if ( material.aoMap ) {
  1119. uniforms.aoMap.value = material.aoMap;
  1120. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1121. }
  1122. // uv repeat and offset setting priorities
  1123. // 1. color map
  1124. // 2. specular map
  1125. // 3. normal map
  1126. // 4. bump map
  1127. // 5. alpha map
  1128. // 6. emissive map
  1129. var uvScaleMap;
  1130. if ( material.map ) {
  1131. uvScaleMap = material.map;
  1132. } else if ( material.specularMap ) {
  1133. uvScaleMap = material.specularMap;
  1134. } else if ( material.displacementMap ) {
  1135. uvScaleMap = material.displacementMap;
  1136. } else if ( material.normalMap ) {
  1137. uvScaleMap = material.normalMap;
  1138. } else if ( material.bumpMap ) {
  1139. uvScaleMap = material.bumpMap;
  1140. } else if ( material.roughnessMap ) {
  1141. uvScaleMap = material.roughnessMap;
  1142. } else if ( material.metalnessMap ) {
  1143. uvScaleMap = material.metalnessMap;
  1144. } else if ( material.alphaMap ) {
  1145. uvScaleMap = material.alphaMap;
  1146. } else if ( material.emissiveMap ) {
  1147. uvScaleMap = material.emissiveMap;
  1148. }
  1149. if ( uvScaleMap !== undefined ) {
  1150. // backwards compatibility
  1151. if ( uvScaleMap.isWebGLRenderTarget ) {
  1152. uvScaleMap = uvScaleMap.texture;
  1153. }
  1154. var offset = uvScaleMap.offset;
  1155. var repeat = uvScaleMap.repeat;
  1156. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1157. }
  1158. }
  1159. function refreshUniformsLine( uniforms, material ) {
  1160. uniforms.diffuse.value = material.color;
  1161. uniforms.opacity.value = material.opacity;
  1162. }
  1163. function refreshUniformsDash( uniforms, material ) {
  1164. uniforms.dashSize.value = material.dashSize;
  1165. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1166. uniforms.scale.value = material.scale;
  1167. }
  1168. function refreshUniformsPoints( uniforms, material ) {
  1169. uniforms.diffuse.value = material.color;
  1170. uniforms.opacity.value = material.opacity;
  1171. uniforms.size.value = material.size * _pixelRatio;
  1172. uniforms.scale.value = _height * 0.5;
  1173. uniforms.map.value = material.map;
  1174. if ( material.map !== null ) {
  1175. var offset = material.map.offset;
  1176. var repeat = material.map.repeat;
  1177. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1178. }
  1179. }
  1180. function refreshUniformsFog( uniforms, fog ) {
  1181. uniforms.fogColor.value = fog.color;
  1182. if ( fog.isFog ) {
  1183. uniforms.fogNear.value = fog.near;
  1184. uniforms.fogFar.value = fog.far;
  1185. } else if ( fog.isFogExp2 ) {
  1186. uniforms.fogDensity.value = fog.density;
  1187. }
  1188. }
  1189. function refreshUniformsLambert( uniforms, material ) {
  1190. if ( material.emissiveMap ) {
  1191. uniforms.emissiveMap.value = material.emissiveMap;
  1192. }
  1193. }
  1194. function refreshUniformsPhong( uniforms, material ) {
  1195. uniforms.specular.value = material.specular;
  1196. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1197. if ( material.emissiveMap ) {
  1198. uniforms.emissiveMap.value = material.emissiveMap;
  1199. }
  1200. if ( material.bumpMap ) {
  1201. uniforms.bumpMap.value = material.bumpMap;
  1202. uniforms.bumpScale.value = material.bumpScale;
  1203. }
  1204. if ( material.normalMap ) {
  1205. uniforms.normalMap.value = material.normalMap;
  1206. uniforms.normalScale.value.copy( material.normalScale );
  1207. }
  1208. if ( material.displacementMap ) {
  1209. uniforms.displacementMap.value = material.displacementMap;
  1210. uniforms.displacementScale.value = material.displacementScale;
  1211. uniforms.displacementBias.value = material.displacementBias;
  1212. }
  1213. }
  1214. function refreshUniformsToon( uniforms, material ) {
  1215. refreshUniformsPhong( uniforms, material );
  1216. if ( material.gradientMap ) {
  1217. uniforms.gradientMap.value = material.gradientMap;
  1218. }
  1219. }
  1220. function refreshUniformsStandard( uniforms, material ) {
  1221. uniforms.roughness.value = material.roughness;
  1222. uniforms.metalness.value = material.metalness;
  1223. if ( material.roughnessMap ) {
  1224. uniforms.roughnessMap.value = material.roughnessMap;
  1225. }
  1226. if ( material.metalnessMap ) {
  1227. uniforms.metalnessMap.value = material.metalnessMap;
  1228. }
  1229. if ( material.emissiveMap ) {
  1230. uniforms.emissiveMap.value = material.emissiveMap;
  1231. }
  1232. if ( material.bumpMap ) {
  1233. uniforms.bumpMap.value = material.bumpMap;
  1234. uniforms.bumpScale.value = material.bumpScale;
  1235. }
  1236. if ( material.normalMap ) {
  1237. uniforms.normalMap.value = material.normalMap;
  1238. uniforms.normalScale.value.copy( material.normalScale );
  1239. }
  1240. if ( material.displacementMap ) {
  1241. uniforms.displacementMap.value = material.displacementMap;
  1242. uniforms.displacementScale.value = material.displacementScale;
  1243. uniforms.displacementBias.value = material.displacementBias;
  1244. }
  1245. if ( material.envMap ) {
  1246. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1247. uniforms.envMapIntensity.value = material.envMapIntensity;
  1248. }
  1249. }
  1250. function refreshUniformsPhysical( uniforms, material ) {
  1251. uniforms.clearCoat.value = material.clearCoat;
  1252. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1253. refreshUniformsStandard( uniforms, material );
  1254. }
  1255. function refreshUniformsDepth( uniforms, material ) {
  1256. if ( material.displacementMap ) {
  1257. uniforms.displacementMap.value = material.displacementMap;
  1258. uniforms.displacementScale.value = material.displacementScale;
  1259. uniforms.displacementBias.value = material.displacementBias;
  1260. }
  1261. }
  1262. function refreshUniformsDistance( uniforms, material ) {
  1263. if ( material.displacementMap ) {
  1264. uniforms.displacementMap.value = material.displacementMap;
  1265. uniforms.displacementScale.value = material.displacementScale;
  1266. uniforms.displacementBias.value = material.displacementBias;
  1267. }
  1268. uniforms.referencePosition.value.copy( material.referencePosition );
  1269. uniforms.nearDistance.value = material.nearDistance;
  1270. uniforms.farDistance.value = material.farDistance;
  1271. }
  1272. function refreshUniformsNormal( uniforms, material ) {
  1273. if ( material.bumpMap ) {
  1274. uniforms.bumpMap.value = material.bumpMap;
  1275. uniforms.bumpScale.value = material.bumpScale;
  1276. }
  1277. if ( material.normalMap ) {
  1278. uniforms.normalMap.value = material.normalMap;
  1279. uniforms.normalScale.value.copy( material.normalScale );
  1280. }
  1281. if ( material.displacementMap ) {
  1282. uniforms.displacementMap.value = material.displacementMap;
  1283. uniforms.displacementScale.value = material.displacementScale;
  1284. uniforms.displacementBias.value = material.displacementBias;
  1285. }
  1286. }
  1287. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1288. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1289. uniforms.ambientLightColor.needsUpdate = value;
  1290. uniforms.directionalLights.needsUpdate = value;
  1291. uniforms.pointLights.needsUpdate = value;
  1292. uniforms.spotLights.needsUpdate = value;
  1293. uniforms.rectAreaLights.needsUpdate = value;
  1294. uniforms.hemisphereLights.needsUpdate = value;
  1295. }
  1296. // GL state setting
  1297. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1298. state.setCullFace( cullFace );
  1299. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  1300. };
  1301. // Textures
  1302. function allocTextureUnit() {
  1303. var textureUnit = _usedTextureUnits;
  1304. if ( textureUnit >= capabilities.maxTextures ) {
  1305. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1306. }
  1307. _usedTextureUnits += 1;
  1308. return textureUnit;
  1309. }
  1310. this.allocTextureUnit = allocTextureUnit;
  1311. // this.setTexture2D = setTexture2D;
  1312. this.setTexture2D = ( function () {
  1313. var warned = false;
  1314. // backwards compatibility: peel texture.texture
  1315. return function setTexture2D( texture, slot ) {
  1316. if ( texture && texture.isWebGLRenderTarget ) {
  1317. if ( ! warned ) {
  1318. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1319. warned = true;
  1320. }
  1321. texture = texture.texture;
  1322. }
  1323. textures.setTexture2D( texture, slot );
  1324. };
  1325. }() );
  1326. this.setTexture = ( function () {
  1327. var warned = false;
  1328. return function setTexture( texture, slot ) {
  1329. if ( ! warned ) {
  1330. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1331. warned = true;
  1332. }
  1333. textures.setTexture2D( texture, slot );
  1334. };
  1335. }() );
  1336. this.setTextureCube = ( function () {
  1337. var warned = false;
  1338. return function setTextureCube( texture, slot ) {
  1339. // backwards compatibility: peel texture.texture
  1340. if ( texture && texture.isWebGLRenderTargetCube ) {
  1341. if ( ! warned ) {
  1342. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1343. warned = true;
  1344. }
  1345. texture = texture.texture;
  1346. }
  1347. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1348. // TODO: unify these code paths
  1349. if ( ( texture && texture.isCubeTexture ) ||
  1350. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1351. // CompressedTexture can have Array in image :/
  1352. // this function alone should take care of cube textures
  1353. textures.setTextureCube( texture, slot );
  1354. } else {
  1355. // assumed: texture property of THREE.WebGLRenderTargetCube
  1356. textures.setTextureCubeDynamic( texture, slot );
  1357. }
  1358. };
  1359. }() );
  1360. this.getRenderTarget = function () {
  1361. return _currentRenderTarget;
  1362. };
  1363. this.setRenderTarget = function ( renderTarget ) {
  1364. _currentRenderTarget = renderTarget;
  1365. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1366. textures.setupRenderTarget( renderTarget );
  1367. }
  1368. var framebuffer = null;
  1369. var isCube = false;
  1370. if ( renderTarget ) {
  1371. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1372. if ( renderTarget.isWebGLRenderTargetCube ) {
  1373. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  1374. isCube = true;
  1375. } else {
  1376. framebuffer = __webglFramebuffer;
  1377. }
  1378. _currentViewport.copy( renderTarget.viewport );
  1379. _currentScissor.copy( renderTarget.scissor );
  1380. _currentScissorTest = renderTarget.scissorTest;
  1381. } else {
  1382. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1383. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1384. _currentScissorTest = _scissorTest;
  1385. }
  1386. if ( _currentFramebuffer !== framebuffer ) {
  1387. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1388. _currentFramebuffer = framebuffer;
  1389. }
  1390. state.viewport( _currentViewport );
  1391. state.scissor( _currentScissor );
  1392. state.setScissorTest( _currentScissorTest );
  1393. if ( isCube ) {
  1394. var textureProperties = properties.get( renderTarget.texture );
  1395. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1396. }
  1397. };
  1398. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1399. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1400. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1401. return;
  1402. }
  1403. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1404. if ( framebuffer ) {
  1405. var restore = false;
  1406. if ( framebuffer !== _currentFramebuffer ) {
  1407. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1408. restore = true;
  1409. }
  1410. try {
  1411. var texture = renderTarget.texture;
  1412. var textureFormat = texture.format;
  1413. var textureType = texture.type;
  1414. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1415. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1416. return;
  1417. }
  1418. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1419. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1420. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  1421. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1422. return;
  1423. }
  1424. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1425. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1426. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1427. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  1428. }
  1429. } else {
  1430. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1431. }
  1432. } finally {
  1433. if ( restore ) {
  1434. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1435. }
  1436. }
  1437. }
  1438. };
  1439. // Map three.js constants to WebGL constants
  1440. function paramThreeToGL( p ) {
  1441. var extension;
  1442. if ( p === RepeatWrapping ) return _gl.REPEAT;
  1443. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  1444. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  1445. if ( p === NearestFilter ) return _gl.NEAREST;
  1446. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  1447. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  1448. if ( p === LinearFilter ) return _gl.LINEAR;
  1449. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  1450. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  1451. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  1452. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  1453. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  1454. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  1455. if ( p === ByteType ) return _gl.BYTE;
  1456. if ( p === ShortType ) return _gl.SHORT;
  1457. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  1458. if ( p === IntType ) return _gl.INT;
  1459. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  1460. if ( p === FloatType ) return _gl.FLOAT;
  1461. if ( p === HalfFloatType ) {
  1462. extension = extensions.get( 'OES_texture_half_float' );
  1463. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  1464. }
  1465. if ( p === AlphaFormat ) return _gl.ALPHA;
  1466. if ( p === RGBFormat ) return _gl.RGB;
  1467. if ( p === RGBAFormat ) return _gl.RGBA;
  1468. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  1469. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  1470. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  1471. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  1472. if ( p === AddEquation ) return _gl.FUNC_ADD;
  1473. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  1474. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  1475. if ( p === ZeroFactor ) return _gl.ZERO;
  1476. if ( p === OneFactor ) return _gl.ONE;
  1477. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  1478. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  1479. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  1480. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  1481. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  1482. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  1483. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  1484. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  1485. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  1486. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  1487. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  1488. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  1489. if ( extension !== null ) {
  1490. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  1491. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  1492. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  1493. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  1494. }
  1495. }
  1496. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  1497. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  1498. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  1499. if ( extension !== null ) {
  1500. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  1501. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  1502. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  1503. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  1504. }
  1505. }
  1506. if ( p === RGB_ETC1_Format ) {
  1507. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  1508. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  1509. }
  1510. if ( p === MinEquation || p === MaxEquation ) {
  1511. extension = extensions.get( 'EXT_blend_minmax' );
  1512. if ( extension !== null ) {
  1513. if ( p === MinEquation ) return extension.MIN_EXT;
  1514. if ( p === MaxEquation ) return extension.MAX_EXT;
  1515. }
  1516. }
  1517. if ( p === UnsignedInt248Type ) {
  1518. extension = extensions.get( 'WEBGL_depth_texture' );
  1519. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  1520. }
  1521. return 0;
  1522. }
  1523. }
  1524. export { WebGLRenderer };
粤ICP备19079148号