Call a kernel function

Call a kernel function

Two kernel functions and the host that calls them. exposure loops over an array<f32> and peak reduces one; the host calls await exposure(1.5, pixels) with a Float32Array and await peak(pixels) for a number. Each loop the compiler proves independent runs on the GPU, one invocation per iteration, and the array comes back in place (Rule 8.22).

Runs on WebGPUCPU tier

The compiler checks this list: a tier is on it exactly when the host's whole run gives the reference with that tier alone. Its journeys gate runs each host on WebGPU and on WebGL2, and its unit suite runs each one on the CPU tier.

"use typeshade";
/* @example
{
"title": "Host: call a kernel function",
"blurb": "Two kernel functions and the host that calls them. `exposure` loops over an `array<f32>` and `peak` reduces one; the host calls `await exposure(1.5, pixels)` with a `Float32Array` and `await peak(pixels)` for a number. Each loop the compiler proves independent runs on the GPU, one invocation per iteration, and the array comes back in place (Rule 8.22).",
"renderable": false,
"reason": "no entry point"
}
*/
// A kernel function: an exported function that takes an array with no size. Each iteration
// writes only its own element, so the loop runs on the GPU, one invocation per element.
export function exposure(gain: f32, pixels: array<f32>) {
for (let i: u32 = 0; i < pixels.length; i++) {
pixels[i] = 1. - exp(-pixels[i] * gain);
}
}
// A reduction: `m = max(m, x)` is folded by the workgroup tree on the GPU, and the return runs
// on the host with what it folded.
export function peak(xs: array<f32>): f32 {
let m = 0.;
for (const x of xs) {
m = max(m, x);
}
return m;
}
// Call kernel functions with plain arguments (surface §65, Rule 8.22).
//
// A kernel function is called like any function the module exports, and awaited. Each loop the
// compiler proves independent runs on the GPU; a typed array it writes comes back in place.
import { exposure, peak } from './host-kernel.shade.ts';
/** Tone-map `n` values on the GPU, then find the brightest. */
export async function run(n = 1024): Promise<{ pixels: Float32Array; peak: number }> {
const pixels = Float32Array.from({ length: n }, (_, i) => (i % 64) / 16);
await exposure(1.5, pixels); // `pixels` now holds the tone-mapped values
const brightest = await peak(pixels); // a number, folded on the GPU
return { pixels, peak: brightest };
}

Both files are the compiler's own at commit 91c2fe31, from the examples directory.

Module on GitHubHost file on GitHub

Edit this page Report a problem