How GPU.js Infers Output Grid Dimensionality

This article explains how GPU.js detects and handles the dimensionality of the execution grid defined by the setOutput() method. By analyzing the structure and length of the argument provided—whether an array or an object—GPU.js determines if the kernel should execute in one, two, or three dimensions. It translates these parameters into WebGL texture bounds and injects coordinate-mapping mathematics into the compiled fragment shader to expose this.thread.x, this.thread.y, and this.thread.z to the developer.

Array-Based Dimensionality Inference

The most common way to define the output shape in GPU.js is via an array of integers. GPU.js directly evaluates the length of this array to infer the grid's dimensions:

Object-Based Dimensionality Inference

GPU.js also accepts an object literal (e.g., { x: 512, y: 512 }). In this case, dimensionality is inferred by checking for the presence of specific coordinate properties:

WebGL Texture Flattening and Coordinate Deconstruction

Because standard WebGL 1.0 and WebGL 2.0 fragment shaders render onto two-dimensional framebuffers (textures), GPU.js must adapt 1D and 3D specifications to fit 2D hardware memory:

During compilation, GPU.js generates specialized GLSL boilerplate prepended to your kernel code. It uses the inferred dimensions to calculate real-time values for this.thread.x, this.thread.y, and this.thread.z from the fragment's 2D canvas coordinates, ensuring seamless access to multi-dimensional indices regardless of the underlying hardware layout.