GPUComputationRenderer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import {
  2. ClampToEdgeWrapping,
  3. DataTexture,
  4. FloatType,
  5. NearestFilter,
  6. RGBAFormat,
  7. ShaderMaterial,
  8. WebGLRenderTarget
  9. } from 'three';
  10. import { FullScreenQuad } from '../postprocessing/Pass.js';
  11. /**
  12. * GPUComputationRenderer, based on SimulationRenderer by zz85
  13. *
  14. * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
  15. * for each compute element (texel)
  16. *
  17. * Each variable has a fragment shader that defines the computation made to obtain the variable in question.
  18. * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
  19. * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
  20. *
  21. * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
  22. * as inputs to render the textures of the next frame.
  23. *
  24. * The render targets of the variables can be used as input textures for your visualization shaders.
  25. *
  26. * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
  27. * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
  28. *
  29. * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
  30. * #DEFINE resolution vec2( 1024.0, 1024.0 )
  31. *
  32. * -------------
  33. *
  34. * Basic use:
  35. *
  36. * // Initialization...
  37. *
  38. * // Create computation renderer
  39. * const gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
  40. *
  41. * // Create initial state float textures
  42. * const pos0 = gpuCompute.createTexture();
  43. * const vel0 = gpuCompute.createTexture();
  44. * // and fill in here the texture data...
  45. *
  46. * // Add texture variables
  47. * const velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, vel0 );
  48. * const posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, pos0 );
  49. *
  50. * // Add variable dependencies
  51. * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
  52. * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
  53. *
  54. * // Add custom uniforms
  55. * velVar.material.uniforms.time = { value: 0.0 };
  56. *
  57. * // Check for completeness
  58. * const error = gpuCompute.init();
  59. * if ( error !== null ) {
  60. * console.error( error );
  61. * }
  62. *
  63. *
  64. * // In each frame...
  65. *
  66. * // Compute!
  67. * gpuCompute.compute();
  68. *
  69. * // Update texture uniforms in your visualization materials with the gpu renderer output
  70. * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
  71. *
  72. * // Do your rendering
  73. * renderer.render( myScene, myCamera );
  74. *
  75. * -------------
  76. *
  77. * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
  78. * Note that the shaders can have multiple input textures.
  79. *
  80. * const myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
  81. * const myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
  82. *
  83. * const inputTexture = gpuCompute.createTexture();
  84. *
  85. * // Fill in here inputTexture...
  86. *
  87. * myFilter1.uniforms.theTexture.value = inputTexture;
  88. *
  89. * const myRenderTarget = gpuCompute.createRenderTarget();
  90. * myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
  91. *
  92. * const outputRenderTarget = gpuCompute.createRenderTarget();
  93. *
  94. * // Now use the output texture where you want:
  95. * myMaterial.uniforms.map.value = outputRenderTarget.texture;
  96. *
  97. * // And compute each frame, before rendering to screen:
  98. * gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
  99. * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
  100. */
  101. class GPUComputationRenderer {
  102. /**
  103. * @param {number} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
  104. * @param {number} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
  105. * @param {WebGLRenderer} renderer The renderer
  106. */
  107. constructor( sizeX, sizeY, renderer ) {
  108. this.variables = [];
  109. this.currentTextureIndex = 0;
  110. let dataType = FloatType;
  111. const passThruUniforms = {
  112. passThruTexture: { value: null }
  113. };
  114. const passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
  115. const quad = new FullScreenQuad( passThruShader );
  116. this.setDataType = function ( type ) {
  117. dataType = type;
  118. return this;
  119. };
  120. this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
  121. const material = this.createShaderMaterial( computeFragmentShader );
  122. const variable = {
  123. name: variableName,
  124. initialValueTexture: initialValueTexture,
  125. material: material,
  126. dependencies: null,
  127. renderTargets: [],
  128. wrapS: null,
  129. wrapT: null,
  130. minFilter: NearestFilter,
  131. magFilter: NearestFilter
  132. };
  133. this.variables.push( variable );
  134. return variable;
  135. };
  136. this.setVariableDependencies = function ( variable, dependencies ) {
  137. variable.dependencies = dependencies;
  138. };
  139. this.init = function () {
  140. if ( renderer.capabilities.maxVertexTextures === 0 ) {
  141. return 'No support for vertex shader textures.';
  142. }
  143. for ( let i = 0; i < this.variables.length; i ++ ) {
  144. const variable = this.variables[ i ];
  145. // Creates rendertargets and initialize them with input texture
  146. variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
  147. variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
  148. this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
  149. this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
  150. // Adds dependencies uniforms to the ShaderMaterial
  151. const material = variable.material;
  152. const uniforms = material.uniforms;
  153. if ( variable.dependencies !== null ) {
  154. for ( let d = 0; d < variable.dependencies.length; d ++ ) {
  155. const depVar = variable.dependencies[ d ];
  156. if ( depVar.name !== variable.name ) {
  157. // Checks if variable exists
  158. let found = false;
  159. for ( let j = 0; j < this.variables.length; j ++ ) {
  160. if ( depVar.name === this.variables[ j ].name ) {
  161. found = true;
  162. break;
  163. }
  164. }
  165. if ( ! found ) {
  166. return 'Variable dependency not found. Variable=' + variable.name + ', dependency=' + depVar.name;
  167. }
  168. }
  169. uniforms[ depVar.name ] = { value: null };
  170. material.fragmentShader = '\nuniform sampler2D ' + depVar.name + ';\n' + material.fragmentShader;
  171. }
  172. }
  173. }
  174. this.currentTextureIndex = 0;
  175. return null;
  176. };
  177. this.compute = function () {
  178. const currentTextureIndex = this.currentTextureIndex;
  179. const nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
  180. for ( let i = 0, il = this.variables.length; i < il; i ++ ) {
  181. const variable = this.variables[ i ];
  182. // Sets texture dependencies uniforms
  183. if ( variable.dependencies !== null ) {
  184. const uniforms = variable.material.uniforms;
  185. for ( let d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
  186. const depVar = variable.dependencies[ d ];
  187. uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
  188. }
  189. }
  190. // Performs the computation for this variable
  191. this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
  192. }
  193. this.currentTextureIndex = nextTextureIndex;
  194. };
  195. this.getCurrentRenderTarget = function ( variable ) {
  196. return variable.renderTargets[ this.currentTextureIndex ];
  197. };
  198. this.getAlternateRenderTarget = function ( variable ) {
  199. return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
  200. };
  201. this.dispose = function () {
  202. quad.dispose();
  203. const variables = this.variables;
  204. for ( let i = 0; i < variables.length; i ++ ) {
  205. const variable = variables[ i ];
  206. if ( variable.initialValueTexture ) variable.initialValueTexture.dispose();
  207. const renderTargets = variable.renderTargets;
  208. for ( let j = 0; j < renderTargets.length; j ++ ) {
  209. const renderTarget = renderTargets[ j ];
  210. renderTarget.dispose();
  211. }
  212. }
  213. };
  214. function addResolutionDefine( materialShader ) {
  215. materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + ' )';
  216. }
  217. this.addResolutionDefine = addResolutionDefine;
  218. // The following functions can be used to compute things manually
  219. function createShaderMaterial( computeFragmentShader, uniforms ) {
  220. uniforms = uniforms || {};
  221. const material = new ShaderMaterial( {
  222. name: 'GPUComputationShader',
  223. uniforms: uniforms,
  224. vertexShader: getPassThroughVertexShader(),
  225. fragmentShader: computeFragmentShader
  226. } );
  227. addResolutionDefine( material );
  228. return material;
  229. }
  230. this.createShaderMaterial = createShaderMaterial;
  231. this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
  232. sizeXTexture = sizeXTexture || sizeX;
  233. sizeYTexture = sizeYTexture || sizeY;
  234. wrapS = wrapS || ClampToEdgeWrapping;
  235. wrapT = wrapT || ClampToEdgeWrapping;
  236. minFilter = minFilter || NearestFilter;
  237. magFilter = magFilter || NearestFilter;
  238. const renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, {
  239. wrapS: wrapS,
  240. wrapT: wrapT,
  241. minFilter: minFilter,
  242. magFilter: magFilter,
  243. format: RGBAFormat,
  244. type: dataType,
  245. depthBuffer: false
  246. } );
  247. return renderTarget;
  248. };
  249. this.createTexture = function () {
  250. const data = new Float32Array( sizeX * sizeY * 4 );
  251. const texture = new DataTexture( data, sizeX, sizeY, RGBAFormat, FloatType );
  252. texture.needsUpdate = true;
  253. return texture;
  254. };
  255. this.renderTexture = function ( input, output ) {
  256. // Takes a texture, and render out in rendertarget
  257. // input = Texture
  258. // output = RenderTarget
  259. passThruUniforms.passThruTexture.value = input;
  260. this.doRenderTarget( passThruShader, output );
  261. passThruUniforms.passThruTexture.value = null;
  262. };
  263. this.doRenderTarget = function ( material, output ) {
  264. const currentRenderTarget = renderer.getRenderTarget();
  265. const currentXrEnabled = renderer.xr.enabled;
  266. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  267. renderer.xr.enabled = false; // Avoid camera modification
  268. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  269. quad.material = material;
  270. renderer.setRenderTarget( output );
  271. quad.render( renderer );
  272. quad.material = passThruShader;
  273. renderer.xr.enabled = currentXrEnabled;
  274. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  275. renderer.setRenderTarget( currentRenderTarget );
  276. };
  277. // Shaders
  278. function getPassThroughVertexShader() {
  279. return 'void main() {\n' +
  280. '\n' +
  281. ' gl_Position = vec4( position, 1.0 );\n' +
  282. '\n' +
  283. '}\n';
  284. }
  285. function getPassThroughFragmentShader() {
  286. return 'uniform sampler2D passThruTexture;\n' +
  287. '\n' +
  288. 'void main() {\n' +
  289. '\n' +
  290. ' vec2 uv = gl_FragCoord.xy / resolution.xy;\n' +
  291. '\n' +
  292. ' gl_FragColor = texture2D( passThruTexture, uv );\n' +
  293. '\n' +
  294. '}\n';
  295. }
  296. }
  297. }
  298. export { GPUComputationRenderer };
粤ICP备19079148号