WebGLBackend.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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, scene = null ) {
  431. return new GLSLNodeBuilder( object, renderer, scene );
  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. this._setupBindings( renderObject.getBindings(), programGPU );
  538. //
  539. this.set( pipeline, {
  540. programGPU
  541. } );
  542. }
  543. createComputePipeline( computePipeline, bindings ) {
  544. const gl = this.gl;
  545. // Program
  546. const fragmentProgram = {
  547. stage: 'fragment',
  548. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  549. };
  550. this.createProgram( fragmentProgram );
  551. const { computeProgram } = computePipeline;
  552. const programGPU = gl.createProgram();
  553. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  554. const vertexShader = this.get( computeProgram ).shaderGPU;
  555. const transforms = computeProgram.transforms;
  556. const transformVaryingNames = [];
  557. const transformAttributeNodes = [];
  558. for ( let i = 0; i < transforms.length; i ++ ) {
  559. const transform = transforms[ i ];
  560. transformVaryingNames.push( transform.varyingName );
  561. transformAttributeNodes.push( transform.attributeNode );
  562. }
  563. gl.attachShader( programGPU, fragmentShader );
  564. gl.attachShader( programGPU, vertexShader );
  565. gl.transformFeedbackVaryings(
  566. programGPU,
  567. transformVaryingNames,
  568. gl.SEPARATE_ATTRIBS,
  569. );
  570. gl.linkProgram( programGPU );
  571. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  572. this._logProgramError( programGPU, fragmentShader, vertexShader );
  573. }
  574. gl.useProgram( programGPU );
  575. // Bindings
  576. this.createBindings( bindings );
  577. this._setupBindings( bindings, programGPU );
  578. const attributeNodes = computeProgram.attributes;
  579. const attributes = [];
  580. const transformBuffers = [];
  581. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  582. const attribute = attributeNodes[ i ].node.attribute;
  583. attributes.push( attribute );
  584. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  585. }
  586. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  587. const attribute = transformAttributeNodes[ i ].attribute;
  588. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  589. const attributeData = this.get( attribute );
  590. transformBuffers.push( attributeData );
  591. }
  592. //
  593. this.set( computePipeline, {
  594. programGPU,
  595. transformBuffers,
  596. attributes
  597. } );
  598. }
  599. createBindings( bindings ) {
  600. this.updateBindings( bindings );
  601. }
  602. updateBindings( bindings ) {
  603. const { gl } = this;
  604. let groupIndex = 0;
  605. let textureIndex = 0;
  606. for ( const binding of bindings ) {
  607. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  608. const bufferGPU = gl.createBuffer();
  609. const data = binding.buffer;
  610. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  611. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  612. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  613. this.set( binding, {
  614. index: groupIndex ++,
  615. bufferGPU
  616. } );
  617. } else if ( binding.isSampledTexture ) {
  618. const { textureGPU, glTextureType } = this.get( binding.texture );
  619. this.set( binding, {
  620. index: textureIndex ++,
  621. textureGPU,
  622. glTextureType
  623. } );
  624. }
  625. }
  626. }
  627. updateBinding( binding ) {
  628. const gl = this.gl;
  629. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  630. const bindingData = this.get( binding );
  631. const bufferGPU = bindingData.bufferGPU;
  632. const data = binding.buffer;
  633. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  634. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  635. }
  636. }
  637. // attributes
  638. createIndexAttribute( attribute ) {
  639. const gl = this.gl;
  640. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  641. }
  642. createAttribute( attribute ) {
  643. if ( this.has( attribute ) ) return;
  644. const gl = this.gl;
  645. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  646. }
  647. createStorageAttribute( attribute ) {
  648. if ( this.has( attribute ) ) return;
  649. const gl = this.gl;
  650. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  651. }
  652. updateAttribute( attribute ) {
  653. this.attributeUtils.updateAttribute( attribute );
  654. }
  655. destroyAttribute( attribute ) {
  656. this.attributeUtils.destroyAttribute( attribute );
  657. }
  658. updateSize() {
  659. //console.warn( 'Abstract class.' );
  660. }
  661. hasFeature( name ) {
  662. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  663. const extensions = this.extensions;
  664. for ( let i = 0; i < keysMatching.length; i ++ ) {
  665. if ( extensions.has( keysMatching[ i ] ) ) return true;
  666. }
  667. return false;
  668. }
  669. getMaxAnisotropy() {
  670. return this.capabilities.getMaxAnisotropy();
  671. }
  672. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  673. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  674. }
  675. copyFramebufferToTexture( texture, renderContext ) {
  676. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  677. }
  678. _setFramebuffer( renderContext ) {
  679. const { gl, state } = this;
  680. let currentFrameBuffer = null;
  681. if ( renderContext.textures !== null ) {
  682. const renderTarget = renderContext.renderTarget;
  683. const renderTargetContextData = this.get( renderTarget );
  684. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  685. const cubeFace = this.renderer._activeCubeFace;
  686. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  687. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  688. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  689. let fb;
  690. if ( isCube ) {
  691. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  692. renderTargetContextData.cubeFramebuffers = [];
  693. }
  694. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  695. } else {
  696. fb = renderTargetContextData.framebuffer;
  697. }
  698. if ( fb === undefined ) {
  699. fb = gl.createFramebuffer();
  700. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  701. const textures = renderContext.textures;
  702. if ( isCube ) {
  703. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  704. const { textureGPU } = this.get( textures[ 0 ] );
  705. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  706. } else {
  707. for ( let i = 0; i < textures.length; i ++ ) {
  708. const texture = textures[ i ];
  709. const textureData = this.get( texture );
  710. textureData.renderTarget = renderContext.renderTarget;
  711. const attachment = gl.COLOR_ATTACHMENT0 + i;
  712. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  713. }
  714. renderTargetContextData.framebuffer = fb;
  715. state.drawBuffers( renderContext, fb );
  716. }
  717. if ( renderContext.depthTexture !== null ) {
  718. const textureData = this.get( renderContext.depthTexture );
  719. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  720. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  721. }
  722. }
  723. if ( samples > 0 ) {
  724. if ( msaaFb === undefined ) {
  725. const invalidationArray = [];
  726. msaaFb = gl.createFramebuffer();
  727. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  728. const msaaRenderbuffers = [];
  729. const textures = renderContext.textures;
  730. for ( let i = 0; i < textures.length; i ++ ) {
  731. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  732. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  733. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  734. if ( depthBuffer ) {
  735. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  736. invalidationArray.push( depthStyle );
  737. }
  738. const texture = renderContext.textures[ i ];
  739. const textureData = this.get( texture );
  740. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  741. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  742. }
  743. renderTargetContextData.msaaFrameBuffer = msaaFb;
  744. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  745. if ( depthRenderbuffer === undefined ) {
  746. depthRenderbuffer = gl.createRenderbuffer();
  747. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  748. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  749. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  750. invalidationArray.push( depthStyle );
  751. }
  752. renderTargetContextData.invalidationArray = invalidationArray;
  753. }
  754. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  755. } else {
  756. currentFrameBuffer = fb;
  757. }
  758. }
  759. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  760. }
  761. _getVaoKey( index, attributes ) {
  762. let key = [];
  763. if ( index !== null ) {
  764. const indexData = this.get( index );
  765. key += ':' + indexData.id;
  766. }
  767. for ( let i = 0; i < attributes.length; i ++ ) {
  768. const attributeData = this.get( attributes[ i ] );
  769. key += ':' + attributeData.id;
  770. }
  771. return key;
  772. }
  773. _createVao( index, attributes ) {
  774. const { gl } = this;
  775. const vaoGPU = gl.createVertexArray();
  776. let key = '';
  777. let staticVao = true;
  778. gl.bindVertexArray( vaoGPU );
  779. if ( index !== null ) {
  780. const indexData = this.get( index );
  781. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  782. key += ':' + indexData.id;
  783. }
  784. for ( let i = 0; i < attributes.length; i ++ ) {
  785. const attribute = attributes[ i ];
  786. const attributeData = this.get( attribute );
  787. key += ':' + attributeData.id;
  788. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  789. gl.enableVertexAttribArray( i );
  790. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  791. let stride, offset;
  792. if ( attribute.isInterleavedBufferAttribute === true ) {
  793. stride = attribute.data.stride * attributeData.bytesPerElement;
  794. offset = attribute.offset * attributeData.bytesPerElement;
  795. } else {
  796. stride = 0;
  797. offset = 0;
  798. }
  799. if ( attributeData.isInteger ) {
  800. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  801. } else {
  802. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  803. }
  804. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  805. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  806. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  807. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  808. }
  809. }
  810. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  811. this.vaoCache[ key ] = vaoGPU;
  812. return { vaoGPU, staticVao };
  813. }
  814. _getTransformFeedback( transformBuffers ) {
  815. let key = '';
  816. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  817. key += ':' + transformBuffers[ i ].id;
  818. }
  819. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  820. if ( transformFeedbackGPU !== undefined ) {
  821. return transformFeedbackGPU;
  822. }
  823. const gl = this.gl;
  824. transformFeedbackGPU = gl.createTransformFeedback();
  825. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  826. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  827. const attributeData = transformBuffers[ i ];
  828. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  829. }
  830. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  831. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  832. return transformFeedbackGPU;
  833. }
  834. _setupBindings( bindings, programGPU ) {
  835. const gl = this.gl;
  836. for ( const binding of bindings ) {
  837. const bindingData = this.get( binding );
  838. const index = bindingData.index;
  839. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  840. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  841. gl.uniformBlockBinding( programGPU, location, index );
  842. } else if ( binding.isSampledTexture ) {
  843. const location = gl.getUniformLocation( programGPU, binding.name );
  844. gl.uniform1i( location, index );
  845. }
  846. }
  847. }
  848. _bindUniforms( bindings ) {
  849. const { gl, state } = this;
  850. for ( const binding of bindings ) {
  851. const bindingData = this.get( binding );
  852. const index = bindingData.index;
  853. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  854. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  855. } else if ( binding.isSampledTexture ) {
  856. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  857. }
  858. }
  859. }
  860. }
  861. export default WebGLBackend;