taichi.js

Modern GPU Compute and Rendering in Javascript

README

taichi.js


taichi.js is a modern GPU computing framework for Javascript. It transforms Javascript functions into WebGPU Compute Shaders for massive parallelization. It is a Javascript version of the Python library Taichi.

Playground


On Chrome v113+, visit https://taichi-js.com/playground/ to see taichi.js in action. The webpage provides an interactive code editor that allows you to write, compile, and run taichi.js code.

Documentation


https://taichi-js.com/docs/docs/basics/getting-started

Sample Program


Provided that there exists a HTML canvas with id result_canvas, the following Javascript code will compute and animate a Julia Set fractal using WebGPU:

  1. ```js
  2. let fractal = async () => {
  3.     await ti.init();

  4.     let n = 320;
  5.     let pixels = ti.Vector.field(4, ti.f32, [2 * n, n]);

  6.     let complex_sqr = (z) => {
  7.         return [z[0] ** 2 - z[1] ** 2, z[1] * z[0] * 2];
  8.     };

  9.     ti.addToKernelScope({ pixels, n, complex_sqr });

  10.     let kernel = ti.kernel((t) => {
  11.         for (let I of ndrange(n * 2, n)) {
  12.             // Automatically parallelized
  13.             let i = I[0];
  14.             let j = I[1];
  15.             let c = [-0.8, cos(t) * 0.2];
  16.             let z = [i / n - 1, j / n - 0.5] * 2;
  17.             let iterations = 0;
  18.             while (z.norm() < 20 && iterations < 50) {
  19.                 z = complex_sqr(z) + c;
  20.                 iterations = iterations + 1;
  21.             }
  22.             pixels[(i, j)] = 1 - iterations * 0.02;
  23.             pixels[(i, j)][3] = 1;
  24.         }
  25.     });

  26.     let htmlCanvas = document.getElementById('result_canvas');
  27.     htmlCanvas.width = 2 * n;
  28.     htmlCanvas.height = n;
  29.     let canvas = new ti.Canvas(htmlCanvas);

  30.     let i = 0;
  31.     async function frame() {
  32.         kernel(i * 0.03);
  33.         i = i + 1;
  34.         canvas.setImage(pixels);
  35.         requestAnimationFrame(frame);
  36.     }
  37.     requestAnimationFrame(frame);
  38. };
  39. fractal();
  40. ```

The canvas will show the following animation: