GPUComputationRenderer.js 10 KB

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