What Does setOutput Do in GPU.js?
The setOutput method in GPU.js is a fundamental
configuration function that defines the dimensions and shape of the
array returned by a GPU-accelerated kernel. This article explains how
setOutput works, its role in allocating GPU execution
threads, how it maps internal thread coordinates, and how it determines
the structure of your output data.
Defining Output Dimensions
When executing a kernel, the GPU needs to know the exact size and
dimensionality of the calculation it must perform. The
setOutput method accepts an array of up to three
integers—[width], [width, height], or
[width, height, depth]—corresponding to 1D, 2D, or 3D data
structures:
- 1D Output:
kernel.setOutput([1000])produces a single array with 1,000 elements. - 2D Output:
kernel.setOutput([512, 512])generates a nested matrix containing 512 rows and 512 columns. - 3D Output:
kernel.setOutput([10, 10, 10])produces a three-dimensional array.
Determining the GPU Thread Grid
Beyond shaping the returned JavaScript array, setOutput
dictates the number of parallel threads dispatched across GPU compute
units. Every unique position in the declared output dimensions
corresponds to an individual execution thread. For example, declaring
setOutput([1920, 1080]) tells GPU.js to instantiate over
two million parallel threads, each running the kernel function
simultaneously to calculate the value of its designated position.
Mapping Internal Thread Coordinates
Inside the kernel function body, setOutput directly
drives the built-in coordinate system:
this.thread.xindexes the first dimension (horizontal coordinate).this.thread.yindexes the second dimension (vertical coordinate).this.thread.zindexes the third dimension (depth coordinate).
Each thread reads these coordinate properties to identify its place within the overall output grid, allowing the kernel to perform spatially distinct calculations—such as reading matching pixel locations from an input texture or computing specific cells in matrix multiplication.
Summary
In GPU.js, calling setOutput is mandatory prior to
executing a kernel. It specifies the physical shape of the returned
JavaScript array, controls the thread allocation across the graphics
hardware, and establishes the index bounds used by
this.thread inside your shader logic.