Pass Multiple 2D Arrays to a GPU.js Kernel
Passing multiple 2D arrays into a single GPU.js kernel allows you to perform parallel matrix operations, such as matrix addition or element-wise transformations, directly on the GPU. By defining multiple parameters in your kernel function and setting appropriate output dimensions, GPU.js automatically maps standard JavaScript nested arrays to GPU textures. This guide covers how to set up the kernel, define multiple 2D array inputs, access array elements using thread indices, and execute the kernel efficiently.
Creating the Kernel with Multiple Inputs
To pass multiple 2D arrays, specify them as separate arguments in the
function passed to gpu.createKernel(). You must also define
the output dimensions to match the shape of the resulting
matrix.
const { GPU } = require('gpu.js');
const gpu = new GPU();
// Define the kernel accepting two 2D arrays: a and b
const addMatrices = gpu.createKernel(function(a, b) {
return a[this.thread.y][this.thread.x] + b[this.thread.y][this.thread.x];
}).setOutput([512, 512]);Accessing 2D Arrays via Thread Indices
GPU.js maps dimensions using Cartesian coordinates:
this.thread.xcorresponds to the column index (horizontal axis).this.thread.ycorresponds to the row index (vertical axis).
When indexing standard row-major 2D JavaScript arrays
(array[row][column]), reference the row with
this.thread.y and the column with
this.thread.x:
const valueA = a[this.thread.y][this.thread.x];
const valueB = b[this.thread.y][this.thread.x];Complete Code Example
The following example initializes two 3x3 matrices, passes them to a single kernel, and outputs their sum:
const { GPU } = require('gpu.js');
const gpu = new GPU();
// 1. Prepare two 2D arrays
const matrixA = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const matrixB = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
];
// 2. Create the kernel with two arguments and a 3x3 output
const addKernels = gpu.createKernel(function(matrix1, matrix2) {
return matrix1[this.thread.y][this.thread.x] + matrix2[this.thread.y][this.thread.x];
}).setOutput([3, 3]);
// 3. Execute the kernel by passing both arrays
const result = addKernels(matrixA, matrixB);
console.log(result);
// Output:
// Float32Array [10, 10, 10]
// Float32Array [10, 10, 10]
// Float32Array [10, 10, 10]Important Considerations
- Dimension Alignment: Ensure the
setOutput([width, height])dimensions match the dimensions of the input arrays to prevent out-of-bounds access errors. - Output Return Type: By default, GPU.js returns
output matrices as typed arrays (
Float32Array). If you require nested JavaScript arrays, call.setOutputToTexture(false)or convert the typed output manually. - Dynamic Sizes: If your matrices change size between
runs, specify dynamic dimensions using graphical pipeline settings or
recreate the kernel with updated
setOutputdimensions, as fixed outputs are compiled into the WebGL shader code.