Define a Basic Kernel Function in GPU.js
This article explains how to define and execute a basic kernel
function using the gpu.createKernel method in GPU.js. You
will learn the fundamental syntax, how to set output dimensions, how to
access thread coordinates, and how to execute parallel computations
directly on your GPU using JavaScript.
1. Initialize GPU.js
To start using GPU.js, instantiate the GPU class. This
creates the execution context needed to compile JavaScript code into
WebGL shader language.
const { GPU } = require('gpu.js'); // For Node.js
// or simply use 'new GPU()' in the browser if included via script tag
const gpu = new GPU();2. Basic Syntax of
gpu.createKernel
The gpu.createKernel method takes a standard JavaScript
function, translates it into WebGL GLSL bytecode, and runs it across
parallel threads on the GPU. You must specify the output dimensions
using the .setOutput() method.
const myKernel = gpu.createKernel(function() {
return this.thread.x;
}).setOutput([5]);In this example:
- The kernel runs across an array of length
5. this.thread.xprovides the index of the current execution thread along the X-axis (from 0 to 4).- The kernel returns an array:
[0, 1, 2, 3, 4].
3. Passing Arguments to a Kernel
Kernels can accept parameters such as arrays, matrices, numbers, or textures. Here is how to add two arrays together element by element:
const addArrays = gpu.createKernel(function(a, b) {
return a[this.thread.x] + b[this.thread.x];
}).setOutput([5]);
const arrayA = [1, 2, 3, 4, 5];
const arrayB = [10, 20, 30, 40, 50];
const result = addArrays(arrayA, arrayB);
console.log(result); // Float32Array [11, 22, 33, 44, 55]4. Working with Multi-Dimensional Dimensions
You can define 2D or 3D output grids by passing multiple dimensions
to .setOutput().
- 1D Grid:
.setOutput([width])usesthis.thread.x - 2D Grid:
.setOutput([width, height])usesthis.thread.xandthis.thread.y - 3D Grid:
.setOutput([width, height, depth])usesthis.thread.x,this.thread.y, andthis.thread.z
Example of a 2D multiplication table:
const matrixMultiplication = gpu.createKernel(function() {
return this.thread.x * this.thread.y;
}).setOutput([5, 5]);
console.log(matrixMultiplication());5. Kernel Limitations to Keep in Mind
When writing code inside gpu.createKernel, keep the
following constraints in mind:
- Pure computation: You cannot access the DOM, global
variables outside the function, or objects like
windowordocument. - Standard JavaScript functions: Native methods like
Math.sin(),Math.floor(), and basic math operators work, but methods likeArray.prototype.push()orStringmanipulations are unsupported. - Return values: Each thread must return a single numeric or color value for its corresponding coordinate.