---
title: "WebGPU and WebGL2 compared: shaders, bindings and compute"
description: "WebGPU and WebGL 2 are browser APIs for GPU work. WebGPU exposes render and compute pipelines; WebGL 2 exposes a graphics pipeline based on OpenGL ES."
url: https://typeshade.dev/guide/concepts/webgpu-and-webgl2/
language: en
---

# WebGPU and WebGL2

WebGPU and WebGL 2 are browser APIs for GPU work. WebGPU exposes render and compute pipelines; WebGL 2 exposes a graphics pipeline based on OpenGL ES.

## When it helps

Choose from the operations your application needs and the devices you support. Native compute and storage-buffer atomics call for a suitable compute API. Existing GLSL rendering may fit WebGL 2.

## Worked example

Check whether an adapter or context is available. If the WebGPU adapter is absent, a WebGL 2 path is useful only when its graphics operations can implement the workload.

API availability check

```js
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl2');
let adapter = null;
try {
  adapter = (await navigator.gpu?.requestAdapter()) ?? null;
} catch {
  adapter = null;
}
```

## Practical limits

A successful availability check does not establish every feature, limit, or texture format you need. Handle device creation failures and test each backend on target devices. API choice alone does not predict performance.

WebGPU and WebGL2 are the browser GPU APIs TypeShade compiles for. WebGPU takes WGSL, binds resources through bind groups and has a compute stage. WebGL2 takes GLSL ES 3.00, binds a uniform block to a binding point and has no compute stage of its own. One TypeShade source compiles for both, and the table below sets them side by side. The sections after it say which side owns the device, the pipelines and the buffers in each of the three ways a host uses a module.

## Comparison

| What differs | WebGPU | WebGL2 |
| --- | --- | --- |
| **Shader language** | WGSL. One module holds every stage. | GLSL ES 3.00. A vertex shader and a fragment shader are linked into one program. |
| **Resource binding** | Bind groups, whose layout `reflect()` reads from the compiled module. | No bind groups. A uniform block binds to a binding point, and a sampler is set through its uniform location. |
| **Compute** | A native `compute` stage. | No native compute stage. TypeShade runs supported `compute` entries as generated GLSL ES 3.00 passes, and the manifest names the entries it cannot lower. |
| **Precision** | A type carries its own width. | Each program declares a default precision above its declarations. |
| **GPU features** | The device is requested with the feature, and the emitted module declares an `enable` line where the feature has one. | The host asks the context for the extension, and the emitted source declares a directive where the extension has one. |
| **Order for an imported module** | Tried first. | Tried second, before the CPU. |

## Ownership

A host uses a TypeShade module one of three ways. It compiles the module and hands the shader text to its own WebGPU or WebGL2 code, which owns the device, the pipelines, the bind groups, the buffers and the textures. It imports the module through the Vite plugin and calls its entry points, and TypeShade's runtime creates those objects for the calls. Or it loads the compiled program into the program runtime and draws it in frames of its own: the runtime creates those objects, and the host keeps its render state and its frame loop. Knowing which side owns what is most of what a first TypeShade program needs.

One row per object a WebGPU application creates, for a host that compiles the module and wires it into its own code.

| Object | What the application does | What TypeShade contributes |
| --- | --- | --- |
| **Device** | Asks for an adapter and a `GPUDevice`, and keeps them for the life of the page. | Nothing. The compiled module touches no WebGPU object. |
| **Pipeline** | Creates a render or compute pipeline and names an entry point for each stage. | The shader text of the module, and the name of every entry point in it. |
| **Bind group layout** | Describes each binding by its group, its index, its kind and the stages that see it. | That same description, read back from the compiled module by `reflect()`. |
| **Buffer** | Allocates the buffer and writes the bytes into it. | The offset, the size and the type of every field of a uniform struct. |
| **Texture and sampler** | Creates them and puts them in a bind group. | The binding the shader declares and the type it expects to find there. |

## Importing a module

A host can import a `.shade.ts` into its own TypeScript through the `typeshade/vite` plugin instead, and call what the module exports. A helper runs on the CPU. A `@compute` entry is `await entry(bindings, workgroups)`, where `workgroups` may also be `{ indirect, offset }`: the three counts an earlier call wrote at element `offset` of a `Buffer<u32>`, read when the call runs. A full-screen `@fragment` entry is `entry(canvas, bindings)`, or `entry(canvas)` when it reads no binding, drawn on WebGPU, then WebGL2, then the CPU. The application's column of the table above is then the runtime's: it requests the device on the first call and every later call shares it, builds each entry's pipeline, packs each binding from the object the call passes, and reads back what a compute entry wrote.

A compute entry also accepts `entry(bindings, workgroups, { constants: { WIDTH: width } })`. The names are the module’s declared overrides; omitted values keep their defaults. The selected values determine the workgroup shape, shared-array lengths and CPU invocation builtins. Calculate workgroup counts for that shape: selection does not change the count you pass. The runtime checks names, scalar ranges and device limits before uploads, and captures constants when the call is made.

The same device and entry reuse a pipeline for the same normalized constants and fp64 flavor. Use a small set of measured sizes. The CPU tier uses generated closures with the same constants and bounded workgroup allocations; barriers still need a GPU tier. WebGL2 pins ordinary constants but refuses a changed workgroup shape or workgroup-array length. The [host-compute example](https://typeshade.dev/guide/examples/host-compute/) shows default, direct-specialized and device-plan calls, including the last partly occupied workgroup.

## Loading a program

A host that draws its own frames, an engine or a renderer, loads each compiled program into the program runtime, `typeshade/runtime`, and runs it there. A program travels as its manifest, one object that holds the shader code, the bindings and the entry points. `packModule(compile(source).module)` returns it, a module's host import gives it as its default export, and it is plain JSON a build can write to disk.

```ts
import { createRuntime } from 'typeshade/runtime'
import scene from './scene.shade.ts' // the manifest

const rt = await createRuntime({ device })
const format = navigator.gpu.getPreferredCanvasFormat()
context.configure({ device, format })
const draw = await rt.load(scene).render({ targets: [format] })

const frame = rt.frame()
frame.pass({ color: [context] }, (pass) => {
  pass.draw(draw, { u: { time } }, { count: 3 })
})
await frame.submit()
```

The runtime then does most of what the table above gives the application. It uses the application's `GPUDevice` when `createRuntime({ device })` names one, and never destroys it, or requests a device with the features and limits the programs need and the limits `createRuntime({ limits })` names. It builds every pipeline and bind group from the layouts in the manifest, packs each binding from the value a draw or a dispatch passes by name, and makes the buffers, textures and samplers. The application writes what the compiler cannot know: each pipeline's targets, depth and topology, and when a frame is drawn. A `GPUBuffer`, `GPUTexture` or `GPUSampler` of its own binds as it is, and the frame's `encoder` and a pass's `raw` encoder take its own commands.

Set a program's overrides by name through `RenderState.constants` for a draw or the `constants` option of `Program.compute()` for a dispatch. The compute pipeline resolves `workgroupShape` from the entry's defaults and selected values; read it before calculating dispatch counts. The runtime checks the selected shape against the active WebGPU device's limits. `Frame.submit()` returns the console's line and dropped-call counts for each recorded entry. A host with a console sink reads those counts to report calls that did not fit in the recording buffer.

A host that enables console recording after the build can pass `repack` from `typeshade/emit` as `createRuntime({ emit: repack })`. Build the manifest with `packModule(module, { ir: true })` so it carries the portable IR. The load-time emitter uses the emit options stored in the manifest and carries no TypeScript front end. The fuse scope, `fuse` from `typeshade/fuse`, stands beside it ([Rule 11.11](https://typeshade.dev/reference/rules/11-11/)). `device.fuse()` records calls without a registration import and loads the planner when needed. The body runs synchronously once; queued calls and reads retain their order. Explicit imports remain supported.

The program runtime accepts WebGPU and WebGL2. The WebGL2 tier draws fragments and runs a compute entry as the GLSL ES 3.00 pass program the manifest carries. It refuses with a \`TypeError\` what it does not support yet, such as a multisampled, layered or 3D texture or a storage texture in a draw, and what only WebGPU has, such as a \`GPUCommandEncoder\`. A fallback for the first group is later work.

## Reflection

`reflect()` reads a compiled module and returns its bindings: the group and index the shader declared, the address space, the access the shader needs, and for a uniform struct the fields with their offsets and sizes under the std140 and std430 layouts. A host builds its bind group layout entries out of that list and packs its uniform buffer from those offsets. The numbers the shader was compiled with are the numbers the host writes, so the two sides stay in step.

```ts
const shader = emitModule(paintModule)
const layout = reflect(paintModule)

for (const group of layout.bindGroups) {
  for (const entry of group.entries) {
    // entry.group, entry.binding, entry.space, entry.access, entry.resourceKind
  }
}

for (const struct of layout.uniforms) {
  for (const field of struct.fields) {
    // field.name, field.type, field.offset, field.size
  }
}
```

A field renamed in the shader changes the reflection at the next build, and the host code that reads the reflection follows it.

## Runtime

A module the host compiles needs nothing of TypeShade in the browser. The compiler runs where the shader text is produced: in a build, in a test, or in an editor through the [language service](https://typeshade.dev/guide/language-service/), and what reaches the browser is the emitted shader source and the host code the application already had. A module the host imports carries `typeshade/runtime` into the bundle, the code its calls run on, and no compiler, because the Vite plugin compiles the module when the bundle is built. A call runs on the first tier the browser has, WebGPU, then WebGL2, then the CPU; `createDevice({ prefer })` opens a device on the first of those tiers that opens, and the tiers after it stay a call’s fallback. A `Buffer` of scalars, which `array()` or `device.array()` makes, keeps an array on the GPU between calls. A host that loads programs into the program runtime ships the same `typeshade/runtime` and the manifests, and no compiler either. TypeShade installs 1 runtime dependency, TypeScript, which `compile()` and the language service read source with.

A host can also open an owner of its calls with `createDevice()` from `typeshade/runtime` ([Rule 11.8](https://typeshade.dev/reference/rules/11-8/)). It opens on the first tier of `prefer` that opens, on a `GPUDevice` the host already has, or on a program runtime's device, `createDevice({ runtime })`. `device.array()` makes the `Buffer`s of scalars its calls take, and `device.fuse()` runs a chain of calls as one plan on that device. Data decides the device of a call. A kernel call or an entry call runs on the device of its owned resources: its `Buffer`s and the textures a device made. A kernel call or an entry call with none runs on the device in use, or on the default owner when no device is in use. A `Uniform` takes no part in this choice, since a call copies its value, and an exported binding belongs to no one device. So either joins a call on any device. After a call on one device writes an exported storage array, a call on another device is a `TypeError` until `read()`. A call that mixes devices is a `TypeError` that names both devices and changes no `Buffer`. A draw with no owned resource, and every call of a `fuse()` scope, keep the default owner, inside a `device.use()` block too. Ownership and lifetime checks still apply. `prefer`, `device` and `runtime` are mutually exclusive source options. The owner also picks the flavor of the emulated double, `createDevice({ fp64Flavor })`, and the time one chunk of a long kernel may take, `createDevice({ timeBudgetMs })`. Omitting `fp64Flavor` means automatic selection from the actual device or context; explicit overrides remain available. `fuse()` works on the default owner as before. `configure()` still works and is deprecated: it prints one warning at its first call. Open a device with `createDevice()`, and make a `Buffer` with `array()` from `typeshade/runtime`. `using _ = device.use()` makes a device the device in use for a block. Inside the block, `zeros()`, `array()`, `uniform()` and `texture()` make what they make on that device, and it stays on that device after the block. The uses are one stack for each instance of the runtime module, so do not await inside a block while other tasks may make resources or calls.

A class that a shader module exports also types the data a host keeps for the GPU. `uniform(Camera, { time: 0 })` makes a `Uniform<Camera>`, and `zeros(Particle, n)` and `array(Particle, data)` make a `Buffer<Particle>`. Set a field with `set` and read it with `get`, as in `camera.pos.set(0, 2, 5)`. A `set` checks each number, writes only a value that changed and records the byte range that changed. A binding the module exports, `export declare const camera: uniform<Camera>`, is the same kind of resource in the host. For an exported storage array that states no size, the host sets the length with `resize(n)` or `set(data)`. A kernel function that returns nothing takes a `Buffer` or a `Uniform` as an argument, and an entry call takes one in its bindings object, an exported binding among them. A `Buffer` of scalars comes from `array(xs)` with a typed array such as `Float32Array`, or filled with 0 by `array(n, 'f32')`; `set(data)` replaces its values, `await read()` returns them as a typed array, and `dispose()` frees it. Every array, collection or binding such a call writes must be a `Buffer`; any other is a `TypeError` at the call. The runtime checks such a call when it is made and records it. The call returns nothing, so the host does not wait for it. The runtime submits the recorded calls in the next task, at a `read()`, or before a call or a draw with plain data only. `await buffer.read()` returns what the calls wrote. Until then, `get`, `set`, `resize` and `needsUpdate` of a `Buffer` that a call writes throw a `TypeError` that says to await `read()` first. A recorded call that fails throws its error at the next `read()` or call, with the line of the failed call. A `Buffer` the failed call wrote keeps the error until `set(data)` or `resize()` gives it new values. On WebGL2, a `read()` of what such a call wrote waits on a fence, but at this compiler pin the WebGL2 tier still reads the values back inside each call. A kernel function on a `Buffer` of structs runs on WebGPU or the CPU tier. A draw takes plain data, and a `Buffer` of scalars for a storage array that states no size. For an exported storage array that states its size, an entry call refuses the `Buffer` and takes a plain array of its elements. A kernel function that returns a result returns a new `Buffer` of it at once when it is called on a resource, and some cases are not supported yet and throw a `TypeError`. Inside a `fuse()` body, a call whose written arrays are all `Buffer`s of scalars is recorded into the plan. A call that writes a host array, or takes a `Buffer` of structs or a `Uniform`, throws a `TypeError` at the call ([Rule 11.13](https://typeshade.dev/reference/rules/11-13/)). The [quick start](https://typeshade.dev/guide/quick-start/) has an example.

A generated kernel, compute-entry or fragment-entry call that reads a `Buffer` whose contents an earlier call failed to write rejects with that same error, before it runs, uploads or submits anything. The rejected call leaves the error on every `Buffer` it would have written, and a rejected draw keeps the canvas image. A call that the compiler proves only writes a destination can recover it, and a successful writer clears the error. `set(data)` and `resize()` give a `Buffer` new values and clear the error. Calls that do not read the failed array continue as usual. Manually encoded program-runtime calls and `Frame` submissions keep their own contracts.

On the CPU tier and in the CPU oracle, the compiler’s own routines, its libm, compute all 19 math functions of its list in place of the JavaScript engine’s `Math`: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `exp`, `exp2`, `log`, `log2`, `ldexp` and `pow` (`a ** b` and `Math.pow`). The result for an `f32` operand is the `f64` routine’s result rounded once to `f32`. The compiler’s tests reproduce the same results on Node and on Bun. At this compiler pin, every operand that was measured has an error under 1 ULP. The measurements are samples, not a proof for every operand. `ldexp` is correctly rounded. No other routine is guaranteed to be correctly rounded. The routines do not promise monotonic results. `Math.sin(t)` inside a `"use typeshade"` function may differ in the last bit from `Math.sin(t)` in host code. `pow` keeps ECMAScript’s special values: `(-2) ** 3` is -8, `(-2) ** 0.5` is NaN and `1 ** Infinity` is NaN. A GPU may give other values for such pairs. On WebGPU (Tint) and on WebGL2 in Chromium, both over SwiftShader, eleven special pairs gave values other than the CPU’s, and `(-2) ** 3` gave 8. A GPU’s functions remain the driver’s.

`buildInfo` reports the package version and a nullable exact source revision. Modified, stale or unstamped builds report `revision: null`. `device.info` and `runtime.info` are frozen, serializable records of the actual opened device or context, readable after loss or disposal. WebGPU identity has explicit provenance and enabled device capabilities; unavailable identity stays unknown. WebGL strings come from the actual context. This information does not identify the tier of each call or send a report. The runtime build, producing compiler and benchmark workload have separate provenance.

## Where WebGL2 differs

The same source compiles for WebGL2, and the host side of it looks different.

- There are no bind groups. A uniform block is bound to a binding point on the linked program and a sampler is set through its uniform location, so a host uses the same reflection in a different shape.
- WebGL2 has no native compute stage. TypeShade lowers supported `compute` entries into GLSL ES 3.00 passes using the WebGL2 runtime. The manifest names entries that cannot be lowered.
- Precision belongs to the source. Every emitted GLSL ES 3.00 program declares its default precision above its declarations, which WGSL has no need of.
- A GPU feature is turned on by the host, which asks the context for the extension, and where the extension has a directive the emitted source declares it as well. [Compiler internals](https://typeshade.dev/guide/internals/) describes how the compiler splits those halves.

## Further reading

- [MDN WebGPU API](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API) and [MDN GPUBindGroupLayout](https://developer.mozilla.org/en-US/docs/Web/API/GPUBindGroupLayout) are the host objects this page names.
- [MDN WebGL2RenderingContext](https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext) is the older context, with the uniform and sampler calls the WebGL2 path uses.
- [WebGPU specification](https://www.w3.org/TR/webgpu/) and the [WebGL2 specification](https://registry.khronos.org/webgl/specs/latest/2.0/) define the two host APIs.

Next in this path: [WGSL and GLSL](https://typeshade.dev/guide/concepts/wgsl-and-glsl/), which prints what one source compiles to on both targets.
