gpu-io

A GPU-accelerated computing library for physics simulations and other mathe...

README

gpu-io


NPM Package
Build Size
NPM Downloads
License

A GPU-accelerated computing library for physics simulations and other mathematical calculations

gpu-io is a WebGL library that helps you easily compose GPU-accelerated computing workflows.  This library can be used for a variety of applications including real-time physics simulations, particle/agent-based simulations, cellular automata, image processing, and general purpose GPU computations.  gpu-io supports rendering directly to the WebGL canvas and has some built-in features that make interactivity easy.  See Examples for more details.

Designed for WebGL 2.0 (if available), with fallbacks to support WebGL 1.0 - so it should run on practically any mobile or older browsers.  WebGPU support is planned in the future.


Motivation


The main motivation behind gpu-io is to make it easier to compose GPU-accelerated applications without worrying too much about low-level WebGL details.  This library manages WebGL state, implements shader and program caching, and deals with issues of available WebGL versions or spec inconsistencies across different browsers/hardware.  It should significantly cut down on the amount of boilerplate code and state management you need to do in your applications.  At the same time, gpu-io gives you enough low-level control to write extremely efficient programs for computationally demanding applications.

As of Feb 2022, WebGL2 has now been rolled out to all major platforms (including mobile Safari and Microsoft Edge) - but even among WebGL2 implementations, there are differences in behavior across browsers (especially mobile).  Additionally, you may still come across non-WebGL2 enabled browsers in the wild for some time.  gpu-io rigorously checks for these gotchas and uses software polyfills to patch any issues so you don't have to worry about it.  gpu-io will also attempt to automatically convert your GLSL3 shader code into GLSL1 so that it can run in WebGL1 in a pinch. See tests/README.md for more information on browser support.

- Use
- API


Installation


Install via npm


npm install gpu-io

And import into your project:

  1. ```js
  2. import { GPUComposer, GPULayer, GPUProgram } from 'gpu-io';
  3. ```


Import into HTML


OR you can add gpu-io.js or gpu-io.min.js to your html directly:

  1. ```html
  2. <html>
  3.   <head>
  4.     <script src="gpu-io.js"></script>
  5.   </head>
  6.   <body>
  7.   </body>
  8. </html>
  9. ```

GPUIO will be accessible globally:

  1. ```js
  2. const { GPUComposer, GPULayer, GPUProgram } = GPUIO;
  3. ```


Use


If you have questions about how to use gpu-io: feel free to start a new discussion thread.

A simple example of how to use gpu-io to simulate 2D diffusion:

  1. ```js
  2. import {
  3.   GPUComposer,
  4.   GPULayer,
  5.   GPUProgram,
  6.   renderAmplitudeProgram,
  7.   FLOAT,
  8.   INT,
  9.   REPEAT,
  10.   NEAREST,
  11. } from 'gpu-io';

  12. // Init a canvas element.
  13. const canvas = document.createElement('canvas');
  14. document.body.appendChild(canvas);

  15. // Init a composer.
  16. const composer = new GPUComposer({ canvas });

  17. // Init a layer of float data filled with noise.
  18. const noise = new Float32Array(canvas.width * canvas.height);
  19. noise.forEach((el, i) => noise[i] = Math.random());
  20. const state = new GPULayer(composer, {
  21.   name: 'state',
  22.   dimensions: [canvas.width, canvas.height],
  23.   numComponents: 1, // Scalar state has one component.
  24.   type: FLOAT,
  25.   filter: NEAREST,
  26.   // Use 2 buffers so we can toggle read/write
  27.   // from one to the other.
  28.   numBuffers: 2,
  29.   wrapX: REPEAT,
  30.   wrapY: REPEAT,
  31.   array: noise,
  32. });

  33. // Init a program to diffuse state.
  34. const diffuseProgram = new GPUProgram(composer, {
  35.   name: 'render',
  36.   fragmentShader: `
  37.     in vec2 v_uv;

  38.     uniform sampler2D u_state;
  39.     uniform vec2 u_pxSize;

  40.     out float out_result;

  41.     void main() {
  42.       // Compute the discrete Laplacian.
  43.       // https://en.wikipedia.org/wiki/Discrete_Laplace_operator
  44.       float center = texture(u_state, v_uv).x;
  45.       float n = texture(u_state, v_uv + vec2(0, u_pxSize.y)).x;
  46.       float s = texture(u_state, v_uv - vec2(0, u_pxSize.y)).x;
  47.       float e = texture(u_state, v_uv + vec2(u_pxSize.x, 0)).x;
  48.       float w = texture(u_state, v_uv - vec2(u_pxSize.x, 0)).x;
  49.       const float diffusionRate = 0.1;
  50.       out_result =
  51.         center + diffusionRate * (n + s + e + w - 4.0 * center);
  52.     }
  53.   `,
  54.   uniforms: [
  55.     { // Index of sampler2D uniform to assign to value "u_state".
  56.       name: 'u_state',
  57.       value: 0,
  58.       type: INT,
  59.     },
  60.     { // Calculate the size of a 1 px step in UV coordinates.
  61.       name: 'u_pxSize',
  62.       value: [1 / canvas.width, 1 / canvas.height],
  63.       type: FLOAT,
  64.     },
  65.   ],
  66. });

  67. // Init a program to render state to canvas.
  68. // See https://github.com/amandaghassaei/gpu-io/tree/main/docs#gpuprogram-helper-functions
  69. // for more built-in GPUPrograms to use.
  70. const renderProgram = renderAmplitudeProgram(composer, {
  71.   name: 'render',
  72.   type: state.type,
  73.   components: 'x',
  74. });

  75. // Simulation/render loop.
  76. function loop() {
  77.   window.requestAnimationFrame(loop);

  78.   // Diffuse state and write result to state.
  79.   composer.step({
  80.     program: diffuseProgram,
  81.     input: state,
  82.     output: state,
  83.   });

  84.   // If no "output", will draw to canvas.
  85.   composer.step({
  86.     program: renderProgram,
  87.     input: state,
  88.   });
  89. }
  90. loop(); // Start animation loop.
  91. ```

Demo this code - You should see the noise slowly blur, refresh the page to start it over.


Examples


Check out the Examples page to really understand how gpu-io works and how to easily create touch interactions in your application.
Source code for all examples can be found in the examples/ folder.

Please let me know if you made somethings with gpu-io!  Feel free to also post a link in the Show and Tell discussions thread.  I'll periodically add some of these to the Examples page as well.


API


Full API documentation can be found in the docs/ folder.

More information about writing GLSL shaders for gpu-io can be found at docs/GLSL.


Compatibility with Threejs


gpu-io can share a webgl context with Threejs so that both libraries will be able to access shared memory on the gpu:

  1. ```js
  2. import THREE from 'three';
  3. import {
  4.   GPUComposer,
  5.   GPULayer,
  6.   FLOAT,
  7.   CLAMP_TO_EDGE,
  8.   LINEAR,
  9. } from 'gpu-io';

  10. const renderer = new THREE.WebGLRenderer();
  11. // Use renderer.autoClear = false if you want to overlay threejs stuff
  12. // on top of things rendered to the screen from gpu-io.
  13. // renderer.autoClear = false;

  14. const composer = GPUComposer.initWithThreeRenderer(renderer);
  15. ```

Data is passed between gpu-io and Threejs via WebGLTextures.  To bind a GPULayer to a Threejs Texture:

  1. ```js
  2. const layer1 = new GPULayer(composer, {
  3.   name: 'layer1',
  4.   dimensions: [100, 100],
  5.   type: FLOAT,
  6.   numComponents: 1,
  7. });

  8. const texture = new THREE.Texture();
  9. // Link webgl texture to threejs object.
  10. layer1.attachToThreeTexture(texture);

  11. // Use texture in threejs scene.
  12. const mesh = new THREE.Mesh(
  13.   new PlaneBufferGeometry(1, 1),
  14.   new MeshBasicMaterial({
  15.     map: texture,
  16.   }),
  17. );

  18. // After threejs initialization - undo any changes threejs has made to WebGL state.
  19. composer.undoThreeState();

  20. loop() {
  21.   // Compute things with gpu-io.
  22.   composer.step({
  23.     program: myProgram,
  24.     output: layer1,
  25.   });

  26.   ....

  27.   // Reset WebGL state back to what threejs is expecting
  28.   // (otherwise we get WebGL errors).
  29.   composer.resetThreeState();
  30.   // Render threejs scene.
  31.   // Updates to layer1 will propagate to texture without any
  32.   // additional needsUpdate flags.
  33.   renderer.render(scene, camera);
  34.   // Undo any changes threejs has made to WebGL state.
  35.   composer.undoThreeState();
  36. }
  37. ```

More info about using gpu-io with Threejs can be found in the Threejs Example.


Limitations/Notes



Limitations


- gpu-io currently only supports GPULayers with 1D or 2D arrays of dense data.  3D textures are not officially supported by the library.  You can still compute 3D simulations in gpu-io, you will just need to pass in your 3D position data as a 1D list to a GPULayer and then access it in the fragment shader using .xyz.  TODO: make example for this.
- gpu-io does not currently allow you to pass in your own vertex shaders.  Currently all computation is happening in user-specified fragment shaders; vertex shaders are managed internally.
- In order for the WRAP/FILTER polyfilling to work correctly, any calls to texture() must contain a direct reference to the sampler2D that it should operate on.  For example:

  1. ```glsl
  2. varying vec2 v_uv;

  3. uniform sampler2D u_sampler1;
  4. uniform sampler2D u_sampler2;

  5. out vec4 out_result;

  6. vec4 lookupSampler2(vec2 uv) {
  7.   // This is good, it passes u_sampler2 directly to texture().
  8.   return texture(u_sampler2, uv);
  9. }

  10. vec4 lookupSampler(sampler2D sampler, vec2 uv) {
  11.   // At compile time it is hard to say which sampler
  12.   // is passed to texture().
  13.   // This will not be polyfilled, it will throw a warning.
  14.   return texture(sampler, uv);
  15. }

  16. void main() {
  17.   // This is good, it passes u_sampler1 directly to texture().
  18.   vec2 position = texture(u_sampler1, v_uv).xy;

  19.   ....
  20. }
  21. ```


GLSL Version


gpu-io defaults to using WebGL2 (if available) with GLSL version 300 (GLSL3) but you can set it to use WebGL1 or GLSL version 100 (GLSL1) by passing contextID or glslVersion parameters to GPUComposer:

  1. ```js
  2. import {
  3.   GPUComposer,
  4.   GLSL1,
  5.   WEBGL1,
  6. } from 'gpu-io';

  7. // Init with WebGL2 (if available) with GLSL1.
  8. const composer1 = new GPUComposer({
  9.   canvas: document.createElement('canvas'),
  10.   glslVersion: GLSL1,
  11. });

  12. // Init with WebGL1 with GLSL1 (GLSL3 is not supported in WebGL1).
  13. const composer2 = new GPUComposer({
  14.   canvas: document.createElement('canvas'),
  15.   contextID: WEBGL1,
  16. });
  17. ```

See docs>GPUComposer>constructor for more information.

gpu-io will automatically convert any GLSL3 shaders to GLSL1 when targeting WebGL1.  If supporting WebGL1/GLSL1 is important to you, see the GLSL1 Support doc for more info about what functions/types/operators are available in gpu-io's flavor of GLSL1.


Transform Feedback


You might notice that gpu-io does not use any transform feedback to handle computations on GPULayers.  Transform feedback is great for things like particle simulations and other types of physics that is computed on the vertex level as opposed to the pixel level.  It is still absolutely possible to perform these types of simulations using gpu-io (see Examples), but currently all the computation happens in a fragment shader.  There are a few reasons for this:

- The main use case for gpu-io is to operate on 2D spatially-distributed state (i.e. fields) stored in textures using fragment shaders.  There is additional support for 1D arrays and lines/particles, but that is secondary functionality.
- Transform feedback is only supported in WebGL2.  At the time I first started writing this in 2020, WebGL2 was not supported by mobile Safari.  Though that has changed recently, for now I'd like to support all functionality in gpu-io in WebGL1/GLSL1 as well.
- The API is simpler if we constrain computations to the fragment shader only.

My current plan is to wait for WebGPU to officially launch by default in some browsers, and then re-evaluate some of the design decisions made in gpu-io.  WebGL puts artificial constraints on the current API by forcing general-purpose computing to happen in a vertex and fragment shader rendering pipeline rather than a compute pipeline, so I'd like to get away from WebGL in the long term – and using transform feedback feels like a step backwards at this point.


Precision


By default all shaders in gpu-io are inited with highp precision floats and ints, but they will fall back to mediump if highp is not available (this is the same convention used by Threejs).  More info in src/glsl/common/precision.ts.

You can override these defaults by specifying intPrecision and floatPrecision in GPUComposer's constructor:
  1. ```js
  2. import {
  3.   GPUComposer,
  4.   PRECISION_LOW_P,
  5.   PRECISION_MEDIUM_P,
  6.   PRECISION_HIGH_P,
  7. } from 'gpu-io';

  8. const composer = new GPUComposer({
  9.   canvas: document.getElementById('webgl-canvas'),
  10.   intPrecision: PRECISION_MEDIUM_P,
  11.   floatPrecision: PRECISION_MEDIUM_P,
  12. });
  13. ```

Of course, you can also always manually specify the precision of a particular variable in your shader code:

  1. ```glsl
  2. in vec2 v_uv;

  3. // u_state is a BYTE array, so we can set its precision to lowp.
  4. uniform lowp isampler2D u_state;

  5. out vec4 out_result;

  6. void main() {
  7.   lowp int state = texture(u_state, v_uv).r;
  8.   ....
  9. }
  10. ```

Note: even if highp is specified in your shader code, gpu-io will convert to mediump if the current browser does not support highp (the alternative would be to throw an error).

I've also included the following helper functions to test the precision of mediump on your device and determine whether highp is supported:

  1. ```js
  2. import {
  3.   isHighpSupportedInVertexShader,
  4.   isHighpSupportedInFragmentShader,
  5.   getVertexShaderMediumpPrecision,
  6.   getFragmentShaderMediumpPrecision,
  7. } from 'gpu-io';

  8. // Prints 'highp' or 'mediump' depending on returned precision of
  9. // mediump (16+bit or 32+bit).
  10. // On many devices (esp desktop) mediump defaults to 32bit.
  11. // See https://webglfundamentals.org/webgl/lessons/webgl-precision-issues.html
  12. // for more info.
  13. console.log(getVertexShaderMediumpPrecision());
  14. console.log(getFragmentShaderMediumpPrecision());

  15. // Print true or false depending on highp support of browser/device.
  16. console.log(isHighpSupportedInVertexShader());
  17. console.log(isHighpSupportedInFragmentShader());
  18. ```


Acknowledgements


I used a few codebases as reference when writing this, thanks to their authors for making these repos available:


Other resources:



License


This work is distributed under an MIT license.  Note that gpu-io depends on a few npm packages:

- @amandaghassaei/type-checks - MIT license, no dependencies.
- @petamoriken/float16 - MIT license, no dependencies.
- changedpi - MIT license, no dependencies.
- file-saver - MIT license, no dependencies.


Development


Update 10/2022:  I'm switching gears a bit to focus on some new projects, but I'll be continuing to use gpu-io as the foundation for almost everything I'm working on.  I expect that some new features will be added to this over the next six months or so, but can't be super involved in helping to debug issues you may run into.  Feel free to log issues, but don't expect a super prompt response! See the Examples for more info about how to use this library.

Pull requests welcome! I hope this library is useful to others, but I also realize that I have some very specific needs that have influenced the direction of this code – so we'll see what happens.  Please let me know if you end up using this, I'd love to see what you're making!


Compiling with Webpack


Compiled with webpack.  To build ts files fromsrc to js in dist run:

  1. ```
  2. npm install
  3. npm run build
  4. ```


Automated Testing


I'm using mocha + karma + chai + headless Chrome to test the components of gpu-io, following the setup described in Automated testing with Headless Chrome.  Those tests are located in tests/mocha/.  To run the automated tests, use:

  1. ```
  2. npm run test
  3. ```

The automated tests do not get full code coverage yet, but I'm planning to add to them when I go back to implement WebGPU features in this library.

Browser/Device Testing


I've also included a webpage for testing various functions of this library in a browser/hardware combo of your choice.  This page is current hosted at apps.amandaghassaei.com/gpu-io/tests/.

Note: The detected OS and browser version may not always be 100% accurate.

See tests/README#browser-support for results of various browser/hardware combos.