WebGLBackend.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  1. import { WebGLCoordinateSystem } from 'three';
  2. import GLSLNodeBuilder from './nodes/GLSLNodeBuilder.js';
  3. import Backend from '../common/Backend.js';
  4. import WebGLAttributeUtils from './utils/WebGLAttributeUtils.js';
  5. import WebGLState from './utils/WebGLState.js';
  6. import WebGLUtils from './utils/WebGLUtils.js';
  7. import WebGLTextureUtils from './utils/WebGLTextureUtils.js';
  8. import WebGLExtensions from './utils/WebGLExtensions.js';
  9. import WebGLCapabilities from './utils/WebGLCapabilities.js';
  10. import { GLFeatureName } from './utils/WebGLConstants.js';
  11. import { WebGLBufferRenderer } from './WebGLBufferRenderer.js';
  12. //
  13. class WebGLBackend extends Backend {
  14. constructor( parameters = {} ) {
  15. super( parameters );
  16. this.isWebGLBackend = true;
  17. }
  18. init( renderer ) {
  19. super.init( renderer );
  20. //
  21. const parameters = this.parameters;
  22. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  23. this.gl = glContext;
  24. this.extensions = new WebGLExtensions( this );
  25. this.capabilities = new WebGLCapabilities( this );
  26. this.attributeUtils = new WebGLAttributeUtils( this );
  27. this.textureUtils = new WebGLTextureUtils( this );
  28. this.bufferRenderer = new WebGLBufferRenderer( this );
  29. this.state = new WebGLState( this );
  30. this.utils = new WebGLUtils( this );
  31. this.vaoCache = {};
  32. this.transformFeedbackCache = {};
  33. this.discard = false;
  34. this.trackTimestamp = ( parameters.trackTimestamp === true );
  35. this.extensions.get( 'EXT_color_buffer_float' );
  36. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  37. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38. this._currentContext = null;
  39. }
  40. get coordinateSystem() {
  41. return WebGLCoordinateSystem;
  42. }
  43. async getArrayBufferAsync( attribute ) {
  44. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45. }
  46. initTimestampQuery( renderContext ) {
  47. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48. const renderContextData = this.get( renderContext );
  49. if ( this.queryRunning ) {
  50. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  51. renderContextData.queryQueue.push( renderContext );
  52. return;
  53. }
  54. if ( renderContextData.activeQuery ) {
  55. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  56. renderContextData.activeQuery = null;
  57. }
  58. renderContextData.activeQuery = this.gl.createQuery();
  59. if ( renderContextData.activeQuery !== null ) {
  60. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  61. this.queryRunning = true;
  62. }
  63. }
  64. // timestamp utils
  65. prepareTimestampBuffer( renderContext ) {
  66. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  67. const renderContextData = this.get( renderContext );
  68. if ( renderContextData.activeQuery ) {
  69. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  70. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  71. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  72. renderContextData.activeQuery = null;
  73. this.queryRunning = false;
  74. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  75. const nextRenderContext = renderContextData.queryQueue.shift();
  76. this.initTimestampQuery( nextRenderContext );
  77. }
  78. }
  79. }
  80. async resolveTimestampAsync( renderContext, type = 'render' ) {
  81. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  82. const renderContextData = this.get( renderContext );
  83. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  84. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  85. const queryInfo = renderContextData.gpuQueries[ i ];
  86. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  87. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  88. if ( available && ! disjoint ) {
  89. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  90. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  91. this.gl.deleteQuery( queryInfo.query );
  92. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  93. i --;
  94. this.renderer.info.updateTimestamp( type, duration );
  95. }
  96. }
  97. }
  98. getContext() {
  99. return this.gl;
  100. }
  101. beginRender( renderContext ) {
  102. const { gl } = this;
  103. const renderContextData = this.get( renderContext );
  104. //
  105. //
  106. this.initTimestampQuery( renderContext );
  107. renderContextData.previousContext = this._currentContext;
  108. this._currentContext = renderContext;
  109. this._setFramebuffer( renderContext );
  110. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  111. //
  112. if ( renderContext.viewport ) {
  113. this.updateViewport( renderContext );
  114. } else {
  115. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  116. }
  117. if ( renderContext.scissor ) {
  118. const { x, y, width, height } = renderContext.scissorValue;
  119. gl.scissor( x, y, width, height );
  120. }
  121. const occlusionQueryCount = renderContext.occlusionQueryCount;
  122. if ( occlusionQueryCount > 0 ) {
  123. // Get a reference to the array of objects with queries. The renderContextData property
  124. // can be changed by another render pass before the async reading of all previous queries complete
  125. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  126. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  127. renderContextData.lastOcclusionObject = null;
  128. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  129. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  130. renderContextData.occlusionQueryIndex = 0;
  131. }
  132. }
  133. finishRender( renderContext ) {
  134. const { gl, state } = this;
  135. const renderContextData = this.get( renderContext );
  136. const previousContext = renderContextData.previousContext;
  137. const textures = renderContext.textures;
  138. if ( textures !== null ) {
  139. for ( let i = 0; i < textures.length; i ++ ) {
  140. const texture = textures[ i ];
  141. if ( texture.generateMipmaps ) {
  142. this.generateMipmaps( texture );
  143. }
  144. }
  145. }
  146. this._currentContext = previousContext;
  147. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  148. const renderTargetContextData = this.get( renderContext.renderTarget );
  149. const { samples } = renderContext.renderTarget;
  150. const fb = renderTargetContextData.framebuffer;
  151. const mask = gl.COLOR_BUFFER_BIT;
  152. if ( samples > 0 ) {
  153. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  154. const textures = renderContext.textures;
  155. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  156. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  157. for ( let i = 0; i < textures.length; i ++ ) {
  158. // TODO Add support for MRT
  159. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  160. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  161. }
  162. }
  163. }
  164. if ( previousContext !== null ) {
  165. this._setFramebuffer( previousContext );
  166. if ( previousContext.viewport ) {
  167. this.updateViewport( previousContext );
  168. } else {
  169. const gl = this.gl;
  170. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  171. }
  172. }
  173. const occlusionQueryCount = renderContext.occlusionQueryCount;
  174. if ( occlusionQueryCount > 0 ) {
  175. const renderContextData = this.get( renderContext );
  176. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  177. const { gl } = this;
  178. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  179. }
  180. this.resolveOccludedAsync( renderContext );
  181. }
  182. this.prepareTimestampBuffer( renderContext );
  183. }
  184. resolveOccludedAsync( renderContext ) {
  185. const renderContextData = this.get( renderContext );
  186. // handle occlusion query results
  187. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  188. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  189. const occluded = new WeakSet();
  190. const { gl } = this;
  191. renderContextData.currentOcclusionQueryObjects = null;
  192. renderContextData.currentOcclusionQueries = null;
  193. const check = () => {
  194. let completed = 0;
  195. // check all queries and requeue as appropriate
  196. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  197. const query = currentOcclusionQueries[ i ];
  198. if ( query === null ) continue;
  199. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  200. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  201. currentOcclusionQueries[ i ] = null;
  202. gl.deleteQuery( query );
  203. completed ++;
  204. }
  205. }
  206. if ( completed < currentOcclusionQueries.length ) {
  207. requestAnimationFrame( check );
  208. } else {
  209. renderContextData.occluded = occluded;
  210. }
  211. };
  212. check();
  213. }
  214. }
  215. isOccluded( renderContext, object ) {
  216. const renderContextData = this.get( renderContext );
  217. return renderContextData.occluded && renderContextData.occluded.has( object );
  218. }
  219. updateViewport( renderContext ) {
  220. const gl = this.gl;
  221. const { x, y, width, height } = renderContext.viewportValue;
  222. gl.viewport( x, y, width, height );
  223. }
  224. setScissorTest( boolean ) {
  225. const gl = this.gl;
  226. if ( boolean ) {
  227. gl.enable( gl.SCISSOR_TEST );
  228. } else {
  229. gl.disable( gl.SCISSOR_TEST );
  230. }
  231. }
  232. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  233. const { gl } = this;
  234. if ( descriptor === null ) {
  235. descriptor = {
  236. textures: null,
  237. clearColorValue: this.getClearColor()
  238. };
  239. }
  240. //
  241. let clear = 0;
  242. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  243. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  244. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  245. if ( clear !== 0 ) {
  246. const clearColor = descriptor.clearColorValue || this.getClearColor();
  247. if ( depth ) this.state.setDepthMask( true );
  248. if ( descriptor.textures === null ) {
  249. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  250. gl.clear( clear );
  251. } else {
  252. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  253. if ( color ) {
  254. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  255. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  256. }
  257. }
  258. if ( depth && stencil ) {
  259. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  260. } else if ( depth ) {
  261. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  262. } else if ( stencil ) {
  263. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  264. }
  265. }
  266. }
  267. }
  268. beginCompute( computeGroup ) {
  269. const gl = this.gl;
  270. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  271. this.initTimestampQuery( computeGroup );
  272. }
  273. compute( computeGroup, computeNode, bindings, pipeline ) {
  274. const gl = this.gl;
  275. if ( ! this.discard ) {
  276. // required here to handle async behaviour of render.compute()
  277. gl.enable( gl.RASTERIZER_DISCARD );
  278. this.discard = true;
  279. }
  280. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  281. const vaoKey = this._getVaoKey( null, attributes );
  282. const vaoGPU = this.vaoCache[ vaoKey ];
  283. if ( vaoGPU === undefined ) {
  284. this._createVao( null, attributes );
  285. } else {
  286. gl.bindVertexArray( vaoGPU );
  287. }
  288. gl.useProgram( programGPU );
  289. this._bindUniforms( bindings );
  290. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  291. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  292. gl.beginTransformFeedback( gl.POINTS );
  293. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  294. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  295. } else {
  296. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  297. }
  298. gl.endTransformFeedback();
  299. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  300. // switch active buffers
  301. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  302. const dualAttributeData = transformBuffers[ i ];
  303. if ( dualAttributeData.pbo ) {
  304. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  305. }
  306. dualAttributeData.switchBuffers();
  307. }
  308. }
  309. finishCompute( computeGroup ) {
  310. const gl = this.gl;
  311. this.discard = false;
  312. gl.disable( gl.RASTERIZER_DISCARD );
  313. this.prepareTimestampBuffer( computeGroup );
  314. }
  315. draw( renderObject/*, info*/ ) {
  316. const { object, pipeline, material, context } = renderObject;
  317. const { programGPU } = this.get( pipeline );
  318. const { gl, state } = this;
  319. const contextData = this.get( context );
  320. //
  321. this._bindUniforms( renderObject.getBindings() );
  322. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  323. state.setMaterial( material, frontFaceCW );
  324. gl.useProgram( programGPU );
  325. //
  326. let vaoGPU = renderObject.staticVao;
  327. if ( vaoGPU === undefined ) {
  328. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  329. vaoGPU = this.vaoCache[ vaoKey ];
  330. if ( vaoGPU === undefined ) {
  331. let staticVao;
  332. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  333. if ( staticVao ) renderObject.staticVao = vaoGPU;
  334. }
  335. }
  336. gl.bindVertexArray( vaoGPU );
  337. //
  338. const index = renderObject.getIndex();
  339. const geometry = renderObject.geometry;
  340. const drawRange = renderObject.drawRange;
  341. const firstVertex = drawRange.start;
  342. //
  343. const lastObject = contextData.lastOcclusionObject;
  344. if ( lastObject !== object && lastObject !== undefined ) {
  345. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  346. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  347. contextData.occlusionQueryIndex ++;
  348. }
  349. if ( object.occlusionTest === true ) {
  350. const query = gl.createQuery();
  351. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  352. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  353. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  354. }
  355. contextData.lastOcclusionObject = object;
  356. }
  357. //
  358. const renderer = this.bufferRenderer;
  359. if ( object.isPoints ) renderer.mode = gl.POINTS;
  360. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  361. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  362. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  363. else {
  364. if ( material.wireframe === true ) {
  365. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  366. renderer.mode = gl.LINES;
  367. } else {
  368. renderer.mode = gl.TRIANGLES;
  369. }
  370. }
  371. //
  372. let count;
  373. renderer.object = object;
  374. if ( index !== null ) {
  375. const indexData = this.get( index );
  376. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  377. renderer.index = index.count;
  378. renderer.type = indexData.type;
  379. count = indexCount;
  380. } else {
  381. renderer.index = 0;
  382. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  383. count = vertexCount;
  384. }
  385. const instanceCount = this.getInstanceCount( renderObject );
  386. if ( object.isBatchedMesh ) {
  387. if ( object._multiDrawInstances !== null ) {
  388. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  389. } else {
  390. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  391. }
  392. } else if ( instanceCount > 1 ) {
  393. renderer.renderInstances( firstVertex, count, instanceCount );
  394. } else {
  395. renderer.render( firstVertex, count );
  396. }
  397. //
  398. gl.bindVertexArray( null );
  399. }
  400. needsRenderUpdate( /*renderObject*/ ) {
  401. return false;
  402. }
  403. getRenderCacheKey( renderObject ) {
  404. return renderObject.id;
  405. }
  406. // textures
  407. createDefaultTexture( texture ) {
  408. this.textureUtils.createDefaultTexture( texture );
  409. }
  410. createTexture( texture, options ) {
  411. this.textureUtils.createTexture( texture, options );
  412. }
  413. updateTexture( texture, options ) {
  414. this.textureUtils.updateTexture( texture, options );
  415. }
  416. generateMipmaps( texture ) {
  417. this.textureUtils.generateMipmaps( texture );
  418. }
  419. destroyTexture( texture ) {
  420. this.textureUtils.destroyTexture( texture );
  421. }
  422. copyTextureToBuffer( texture, x, y, width, height ) {
  423. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  424. }
  425. createSampler( /*texture*/ ) {
  426. //console.warn( 'Abstract class.' );
  427. }
  428. destroySampler() {}
  429. // node builder
  430. createNodeBuilder( object, renderer ) {
  431. return new GLSLNodeBuilder( object, renderer );
  432. }
  433. // program
  434. createProgram( program ) {
  435. const gl = this.gl;
  436. const { stage, code } = program;
  437. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  438. gl.shaderSource( shader, code );
  439. gl.compileShader( shader );
  440. this.set( program, {
  441. shaderGPU: shader
  442. } );
  443. }
  444. destroyProgram( /*program*/ ) {
  445. console.warn( 'Abstract class.' );
  446. }
  447. createRenderPipeline( renderObject, promises ) {
  448. const gl = this.gl;
  449. const pipeline = renderObject.pipeline;
  450. // Program
  451. const { fragmentProgram, vertexProgram } = pipeline;
  452. const programGPU = gl.createProgram();
  453. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  454. const vertexShader = this.get( vertexProgram ).shaderGPU;
  455. gl.attachShader( programGPU, fragmentShader );
  456. gl.attachShader( programGPU, vertexShader );
  457. gl.linkProgram( programGPU );
  458. this.set( pipeline, {
  459. programGPU,
  460. fragmentShader,
  461. vertexShader
  462. } );
  463. if ( promises !== null && this.parallel ) {
  464. const p = new Promise( ( resolve /*, reject*/ ) => {
  465. const parallel = this.parallel;
  466. const checkStatus = () => {
  467. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  468. this._completeCompile( renderObject, pipeline );
  469. resolve();
  470. } else {
  471. requestAnimationFrame( checkStatus );
  472. }
  473. };
  474. checkStatus();
  475. } );
  476. promises.push( p );
  477. return;
  478. }
  479. this._completeCompile( renderObject, pipeline );
  480. }
  481. _handleSource( string, errorLine ) {
  482. const lines = string.split( '\n' );
  483. const lines2 = [];
  484. const from = Math.max( errorLine - 6, 0 );
  485. const to = Math.min( errorLine + 6, lines.length );
  486. for ( let i = from; i < to; i ++ ) {
  487. const line = i + 1;
  488. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  489. }
  490. return lines2.join( '\n' );
  491. }
  492. _getShaderErrors( gl, shader, type ) {
  493. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  494. const errors = gl.getShaderInfoLog( shader ).trim();
  495. if ( status && errors === '' ) return '';
  496. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  497. if ( errorMatches ) {
  498. const errorLine = parseInt( errorMatches[ 1 ] );
  499. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  500. } else {
  501. return errors;
  502. }
  503. }
  504. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  505. if ( this.renderer.debug.checkShaderErrors ) {
  506. const gl = this.gl;
  507. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  508. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  509. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  510. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  511. } else {
  512. // default error reporting
  513. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  514. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  515. console.error(
  516. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  517. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  518. 'Program Info Log: ' + programLog + '\n' +
  519. vertexErrors + '\n' +
  520. fragmentErrors
  521. );
  522. }
  523. } else if ( programLog !== '' ) {
  524. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  525. }
  526. }
  527. }
  528. _completeCompile( renderObject, pipeline ) {
  529. const gl = this.gl;
  530. const pipelineData = this.get( pipeline );
  531. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  532. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  533. this._logProgramError( programGPU, fragmentShader, vertexShader );
  534. }
  535. gl.useProgram( programGPU );
  536. // Bindings
  537. const bindings = renderObject.getBindings();
  538. this._setupBindings( bindings, programGPU );
  539. //
  540. this.set( pipeline, {
  541. programGPU
  542. } );
  543. }
  544. createComputePipeline( computePipeline, bindings ) {
  545. const gl = this.gl;
  546. // Program
  547. const fragmentProgram = {
  548. stage: 'fragment',
  549. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  550. };
  551. this.createProgram( fragmentProgram );
  552. const { computeProgram } = computePipeline;
  553. const programGPU = gl.createProgram();
  554. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  555. const vertexShader = this.get( computeProgram ).shaderGPU;
  556. const transforms = computeProgram.transforms;
  557. const transformVaryingNames = [];
  558. const transformAttributeNodes = [];
  559. for ( let i = 0; i < transforms.length; i ++ ) {
  560. const transform = transforms[ i ];
  561. transformVaryingNames.push( transform.varyingName );
  562. transformAttributeNodes.push( transform.attributeNode );
  563. }
  564. gl.attachShader( programGPU, fragmentShader );
  565. gl.attachShader( programGPU, vertexShader );
  566. gl.transformFeedbackVaryings(
  567. programGPU,
  568. transformVaryingNames,
  569. gl.SEPARATE_ATTRIBS
  570. );
  571. gl.linkProgram( programGPU );
  572. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  573. this._logProgramError( programGPU, fragmentShader, vertexShader );
  574. }
  575. gl.useProgram( programGPU );
  576. // Bindings
  577. this.createBindings( null, bindings );
  578. this._setupBindings( bindings, programGPU );
  579. const attributeNodes = computeProgram.attributes;
  580. const attributes = [];
  581. const transformBuffers = [];
  582. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  583. const attribute = attributeNodes[ i ].node.attribute;
  584. attributes.push( attribute );
  585. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  586. }
  587. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  588. const attribute = transformAttributeNodes[ i ].attribute;
  589. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  590. const attributeData = this.get( attribute );
  591. transformBuffers.push( attributeData );
  592. }
  593. //
  594. this.set( computePipeline, {
  595. programGPU,
  596. transformBuffers,
  597. attributes
  598. } );
  599. }
  600. createBindings( bindGroup, bindings ) {
  601. this.updateBindings( bindGroup, bindings );
  602. }
  603. updateBindings( bindGroup, bindings ) {
  604. const { gl } = this;
  605. let groupIndex = 0;
  606. let textureIndex = 0;
  607. for ( const bindGroup of bindings ) {
  608. for ( const binding of bindGroup.bindings ) {
  609. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  610. const bufferGPU = gl.createBuffer();
  611. const data = binding.buffer;
  612. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  613. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  614. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  615. this.set( binding, {
  616. index: groupIndex ++,
  617. bufferGPU
  618. } );
  619. } else if ( binding.isSampledTexture ) {
  620. const { textureGPU, glTextureType } = this.get( binding.texture );
  621. this.set( binding, {
  622. index: textureIndex ++,
  623. textureGPU,
  624. glTextureType
  625. } );
  626. }
  627. }
  628. }
  629. }
  630. updateBinding( binding ) {
  631. const gl = this.gl;
  632. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  633. const bindingData = this.get( binding );
  634. const bufferGPU = bindingData.bufferGPU;
  635. const data = binding.buffer;
  636. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  637. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  638. }
  639. }
  640. // attributes
  641. createIndexAttribute( attribute ) {
  642. const gl = this.gl;
  643. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  644. }
  645. createAttribute( attribute ) {
  646. if ( this.has( attribute ) ) return;
  647. const gl = this.gl;
  648. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  649. }
  650. createStorageAttribute( attribute ) {
  651. if ( this.has( attribute ) ) return;
  652. const gl = this.gl;
  653. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  654. }
  655. updateAttribute( attribute ) {
  656. this.attributeUtils.updateAttribute( attribute );
  657. }
  658. destroyAttribute( attribute ) {
  659. this.attributeUtils.destroyAttribute( attribute );
  660. }
  661. updateSize() {
  662. //console.warn( 'Abstract class.' );
  663. }
  664. hasFeature( name ) {
  665. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  666. const extensions = this.extensions;
  667. for ( let i = 0; i < keysMatching.length; i ++ ) {
  668. if ( extensions.has( keysMatching[ i ] ) ) return true;
  669. }
  670. return false;
  671. }
  672. getMaxAnisotropy() {
  673. return this.capabilities.getMaxAnisotropy();
  674. }
  675. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  676. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  677. }
  678. copyFramebufferToTexture( texture, renderContext ) {
  679. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  680. }
  681. _setFramebuffer( renderContext ) {
  682. const { gl, state } = this;
  683. let currentFrameBuffer = null;
  684. if ( renderContext.textures !== null ) {
  685. const renderTarget = renderContext.renderTarget;
  686. const renderTargetContextData = this.get( renderTarget );
  687. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  688. const cubeFace = this.renderer._activeCubeFace;
  689. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  690. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  691. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  692. let fb;
  693. if ( isCube ) {
  694. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  695. renderTargetContextData.cubeFramebuffers = [];
  696. }
  697. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  698. } else {
  699. fb = renderTargetContextData.framebuffer;
  700. }
  701. if ( fb === undefined ) {
  702. fb = gl.createFramebuffer();
  703. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  704. const textures = renderContext.textures;
  705. if ( isCube ) {
  706. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  707. const { textureGPU } = this.get( textures[ 0 ] );
  708. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  709. } else {
  710. for ( let i = 0; i < textures.length; i ++ ) {
  711. const texture = textures[ i ];
  712. const textureData = this.get( texture );
  713. textureData.renderTarget = renderContext.renderTarget;
  714. const attachment = gl.COLOR_ATTACHMENT0 + i;
  715. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  716. }
  717. renderTargetContextData.framebuffer = fb;
  718. state.drawBuffers( renderContext, fb );
  719. }
  720. if ( renderContext.depthTexture !== null ) {
  721. const textureData = this.get( renderContext.depthTexture );
  722. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  723. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  724. }
  725. }
  726. if ( samples > 0 ) {
  727. if ( msaaFb === undefined ) {
  728. const invalidationArray = [];
  729. msaaFb = gl.createFramebuffer();
  730. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  731. const msaaRenderbuffers = [];
  732. const textures = renderContext.textures;
  733. for ( let i = 0; i < textures.length; i ++ ) {
  734. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  735. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  736. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  737. if ( depthBuffer ) {
  738. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  739. invalidationArray.push( depthStyle );
  740. }
  741. const texture = renderContext.textures[ i ];
  742. const textureData = this.get( texture );
  743. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  744. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  745. }
  746. renderTargetContextData.msaaFrameBuffer = msaaFb;
  747. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  748. if ( depthRenderbuffer === undefined ) {
  749. depthRenderbuffer = gl.createRenderbuffer();
  750. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  751. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  752. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  753. invalidationArray.push( depthStyle );
  754. }
  755. renderTargetContextData.invalidationArray = invalidationArray;
  756. }
  757. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  758. } else {
  759. currentFrameBuffer = fb;
  760. }
  761. }
  762. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  763. }
  764. _getVaoKey( index, attributes ) {
  765. let key = [];
  766. if ( index !== null ) {
  767. const indexData = this.get( index );
  768. key += ':' + indexData.id;
  769. }
  770. for ( let i = 0; i < attributes.length; i ++ ) {
  771. const attributeData = this.get( attributes[ i ] );
  772. key += ':' + attributeData.id;
  773. }
  774. return key;
  775. }
  776. _createVao( index, attributes ) {
  777. const { gl } = this;
  778. const vaoGPU = gl.createVertexArray();
  779. let key = '';
  780. let staticVao = true;
  781. gl.bindVertexArray( vaoGPU );
  782. if ( index !== null ) {
  783. const indexData = this.get( index );
  784. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  785. key += ':' + indexData.id;
  786. }
  787. for ( let i = 0; i < attributes.length; i ++ ) {
  788. const attribute = attributes[ i ];
  789. const attributeData = this.get( attribute );
  790. key += ':' + attributeData.id;
  791. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  792. gl.enableVertexAttribArray( i );
  793. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  794. let stride, offset;
  795. if ( attribute.isInterleavedBufferAttribute === true ) {
  796. stride = attribute.data.stride * attributeData.bytesPerElement;
  797. offset = attribute.offset * attributeData.bytesPerElement;
  798. } else {
  799. stride = 0;
  800. offset = 0;
  801. }
  802. if ( attributeData.isInteger ) {
  803. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  804. } else {
  805. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  806. }
  807. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  808. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  809. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  810. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  811. }
  812. }
  813. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  814. this.vaoCache[ key ] = vaoGPU;
  815. return { vaoGPU, staticVao };
  816. }
  817. _getTransformFeedback( transformBuffers ) {
  818. let key = '';
  819. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  820. key += ':' + transformBuffers[ i ].id;
  821. }
  822. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  823. if ( transformFeedbackGPU !== undefined ) {
  824. return transformFeedbackGPU;
  825. }
  826. const gl = this.gl;
  827. transformFeedbackGPU = gl.createTransformFeedback();
  828. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  829. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  830. const attributeData = transformBuffers[ i ];
  831. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  832. }
  833. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  834. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  835. return transformFeedbackGPU;
  836. }
  837. _setupBindings( bindings, programGPU ) {
  838. const gl = this.gl;
  839. for ( const bindGroup of bindings ) {
  840. for ( const binding of bindGroup.bindings ) {
  841. const bindingData = this.get( binding );
  842. const index = bindingData.index;
  843. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  844. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  845. gl.uniformBlockBinding( programGPU, location, index );
  846. } else if ( binding.isSampledTexture ) {
  847. const location = gl.getUniformLocation( programGPU, binding.name );
  848. gl.uniform1i( location, index );
  849. }
  850. }
  851. }
  852. }
  853. _bindUniforms( bindings ) {
  854. const { gl, state } = this;
  855. for ( const bindGroup of bindings ) {
  856. for ( const binding of bindGroup.bindings ) {
  857. const bindingData = this.get( binding );
  858. const index = bindingData.index;
  859. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  860. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  861. } else if ( binding.isSampledTexture ) {
  862. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  863. }
  864. }
  865. }
  866. }
  867. }
  868. export default WebGLBackend;