WGSL shaders: WebGPU vs WebAssembly
Pick an effect, or edit the shader. The page runs the same WGSL on your GPU
with WebGPU, and as WebAssembly that it compiles in your browser with
wgsl-to-wasm.wasm. Then it
compares the two outputs float for float. Nothing is uploaded.
WebGPU
WebAssembly
Absolute difference ×65,536: black → red → yellow. Hover or focus to magnify.
Loading…
Why the outputs can differ #
Wasm f32 arithmetic is IEEE 754 with correct rounding, so the Wasm output is
the same on every machine. WGSL lets GPUs compute sqrt and division less
precisely, and shader compilers can reorder or fuse floating-point operations.
Wasm has no sin, cos, tan, asin, atan, tanh, exp, log or pow
instructions, so the compiler inlines its own polynomial approximations. They
are accurate to about 3 ULP
(pow loses more as its result grows, and atan2 is accurate to 2.4e-7
absolute, which is many ULP when its result is near zero), while GPUs may trade accuracy for speed:
WGSL allows sin an absolute error of 2⁻¹¹ in [−π, π] and does not bound it
outside that range. Small differences can be a few ULP (units in the last place). The heatmap scales
brightness by the largest absolute channel difference times the gain:
zero is black, and a difference of 1/gain or more is yellow. The gain is
65,536. Hover over the difference image or focus it with the keyboard to raise
the gain to 1,048,576 and inspect tiny errors. The
summary still counts every float mismatch. The ULP count
looks large near zero, where adjacent floats are closest
together: 7e-7 can be hundreds of ULP. Comic book, Bulge,
Halftone dots and Fluted glass compare floats or turn them into pixel indexes, so a one-ULP
change could move an outline or a sampled pixel; whether it does depends on the
GPU and the image. With the zigzag or pattern flutes, a few pixels on flute
boundaries often sample a different flute. Voronoi hashes each cell with
fract of products near 400, so GPU rounding moves cell centres slightly and
pixels on cell edges can differ by a few 8-bit levels. Image dithering's
random type uses the same kind of hash, so a few pixels can switch color; its
Bayer types use exact thresholds. The Photo Booth distortions sample
bilinearly, so a small error in a sample position only nudges the blend
between neighbouring pixels. Twirl and Stretch use sin and cos, so they
can differ a little more.
Mirror and Pop art index with integers, so they should match bit for
bit.
How it works #
Each shader reads one array<vec4f> of RGBA32F pixels (16 bytes each),
up to 512×512. Most shaders write one vec4f per invocation; Atkinson dither
writes an 8×8 block. Pixel values are the image's sRGB values divided by 255,
without conversion to linear light.
- WebGPU: the page creates a compute pipeline with
layout: "auto", passes
each override as a pipeline constant, dispatches one invocation per pixel,
and copies the output buffer back.
- WebAssembly:
wgsl-to-wasm.wasm compiles the source to a QIP
content component. Each override becomes a uniform_set_<name> export, and
render runs the entry point once per element with SIMD for vec4f.
Chromatic aberration is a fragment shader instead. Its
@fragment fn main(@builtin(position) pos: vec4f) -> @location(0) vec4f runs
once per pixel and returns that pixel's color. It reads the image from a
texture_2d<f32> with textureLoad and textureDimensions.
- WebGPU: the page draws one triangle over an rgba32float texture cleared
to transparent black, with the image in a second rgba32float texture.
- WebAssembly:
render calls the entry point for each pixel in row order,
with pos set to (x + 0.5, y + 0.5, 0, 1) as on the GPU. The module has
its own width uniform for the rows, so the shader cannot declare one.
discard leaves the pixel transparent black, the same as the GPU's cleared
texture. A textureLoad outside the image is limited as Chrome's Dawn
does, to min(u32(c), size - 1), so a negative coordinate reads the last
column or row. WGSL allows any pixel or zero, so the example clamps its
coordinates itself.
vec2i and vec2u support constructors, conversions, .x, .y and
swizzles, and + - *.
Rings uses fwidth to antialias its edges. GPUs compute dpdx, dpdy and
fwidth from the 2×2 square of pixels that each pixel belongs to, so the Wasm
render runs each 2×2 square together. It runs the shader for all four pixels,
including pixels past an odd right or bottom edge, whose output it drops as the
GPU does. Each derivative call records its argument, and the derivative is the
difference between neighbours in the same row or column of the square. Chrome
on a Mac computes the Coarse forms per row and column too, which WGSL
allows, so the Wasm render does the same. A pixel that discards inside an
if keeps running, so its neighbours still get its values. The shader runs at
least twice per pixel, plus once more for each derivative of a derivative.
The page sets width to the image width. A trailing // min..max comment on an
override gives it a slider. The compiler accepts a subset of WGSL. Helper
functions compile to Wasm functions; they must come before the entry point and
call only helpers above them. Loops must be
for (var i = start; i < N; i++), where the bound and step are integer
literals or consts, the comparison runs the way the step does, and the body
doesn't assign i. They may use break and continue; while and loop
are unsupported. A module-scope const array of literals, such as
const BAYER4 = array<f32, 16>(…), becomes a data segment, and an index past
the end reads the last element, as Chrome does. Shaders with loops, helper
calls or constant-array reads keep the scalar path when vectorized. Run it on the command line with npx qipdo:
npx qipdo qip.dev -i edges.wgsl -o edges.wasm text/wgsl/wgsl-to-wasm.wasm
npx qipdo -i photo.rgba32f -o edges.rgba32f edges.wasm -u width=256 -u threshold=0.3
Enable Vectorize Wasm invocations to compile eligible shaders in groups of
four invocations with SIMD. The caption reports when a shader keeps the scalar
path. The option is off by default: generated modules are larger and simple
shaders can be slower. To use it from the CLI, pass
-u vectorize_invocations=1 to wgsl-to-wasm.wasm when compiling.
To add an effect, add a <script type="text/wgsl" data-name="…"> block to
this page.
Atkinson dither converts luma to black and white in independent 8×8 blocks.
Each pixel sends one eighth of its rounding error to six later neighbours.
Error resets at block edges, so the pattern can repeat every eight pixels.
The page generates unrolled WGSL, written before the compiler supported
loops. Adjust threshold to change the balance of black and white.
Perlin noise generates a two-color field from 3D gradient noise with
quintic interpolation and up to eight octaves. Like the
Paper Perlin noise example, it has
controls for color balance, edge softness, persistence, and lacunarity.
Move time to explore the third dimension. It ignores the input image except
for its dimensions. This implementation uses an integer lattice hash, so its
patterns differ from Paper's GLSL shader.
Halftone dots is a port of the classic dot style from
Paper's Halftone Dots
(GLSL source).
Each dot's size follows the luma at its centre. Set grid to 1 for
hex rows or 0 for a square grid. spacing is the distance between dots in
pixels. Paper Shaders is licensed under the
Apache License 2.0
(NOTICE: “Powered by Paper Shaders: https://shaders.paper.design”). We changed the shader to fit what the compiler
supported when it was ported:
- The four overlapping dot samples are unrolled, in place of loops and helper
functions.
- An algebraic sigmoid,
0.5 + 0.5·s / √(1 + s²), replaces Paper's logistic
contrast curve. It has the same slope at mid-grey.
- A fixed one-pixel edge replaces
fwidth antialiasing.
- The image is sampled nearest-neighbour.
- Dot spacing is set in pixels, in place of Paper's
size.
- Only the classic dots are included. The gooey, holes and soft styles, original
colors, and grain are left out.
Fluted glass, Waves, Spiral and Swirl are ports of
Paper's Fluted Glass,
Waves,
Spiral and
Swirl, from the GLSL at the same commit
(fluted glass,
waves,
spiral,
swirl),
under the same licence. Fluted glass refracts the image through vertical flutes:
shape picks lines, irregular lines, wave, zigzag or pattern flutes, and
distortion_shape picks prism, lens, contour, cascade or flat glass. The other
three draw patterns and ignore the input image except for its dimensions. The
defaults follow Paper's default presets, with time at 0. We changed them to
fit what the compiler supported when they were ported:
- Each
fwidth(f) becomes |f(x + 1, y) − f(x, y)| + |f(x, y + 1) − f(x, y)|,
so the page generates the code that computes f three times. Fluted glass
uses the undistorted pixel size at the image's edges.
- Helper functions, including simplex noise, are inlined, and Swirl's color
loop is unrolled to three bands.
- Pixels are measured in image pixels, with a device pixel ratio of 1. Fluted
glass defaults to
size 0.77 so that flutes on a 512-pixel image are about as
wide as Paper's default on a full-size canvas.
- Waves, Spiral and Swirl output opaque colors. Fluted glass keeps Paper's
transparent background but outputs straight rather than premultiplied alpha.
- Fluted glass leaves out the margins, blur and grain, and it samples the image
bilinearly in the shader.
pow is kept defined: the contour glass takes abs before its even power,
and Swirl clamps noise below 0. Swirl keeps its smoothstep edges apart,
including when twist or softness is 0.
- The color-banding dither is left out, because it scales
sin by 43,758 and
would turn GPU rounding into visible noise.
Mesh gradient, Neuro noise, Dot grid and Voronoi are ports of
Paper's Mesh Gradient,
Neuro Noise,
Dot Grid and
Voronoi, from the GLSL at the same commit
(mesh gradient,
neuro noise,
dot grid,
Voronoi),
under the same licence. All four draw patterns, ignore the input image except
for its dimensions, and output opaque colors. The defaults follow Paper's
default presets, with time at 0. We changed them to fit what the compiler supported when they were ported:
- Mesh gradient now uses a WGSL loop for its two distortion passes. Its color
spots, neuro noise's 15 layers, and Voronoi's 3×3 and 5×5 cell searches remain
unrolled. Mesh gradient has up to four colors and Voronoi up to three, in place of Paper's
ten and five.
- Mesh gradient leaves out both grain effects.
- Voronoi uses Paper's
hash22 in place of its noise texture, so its cells
differ from Paper's.
- Dot grid's
fwidth follows the Fluted glass approach, but it measures the
neighbours from this pixel's cell so cell boundaries don't show.
- Dot sizes and gaps are in image pixels, with a device pixel ratio of 1.
- Colors are clamped to [0, 1], as Paper's framebuffer does: neuro noise
reaches 1.4, Voronoi's glow can overshoot, and dot grid's opacity randomizer
can exceed 1.
pow is kept defined: mesh gradient floors its distance before raising it
to 3.5, and Voronoi writes pow(glow, 1.5) as glow · √glow. Dot grid keeps
its smoothstep edges apart where the distance is flat.
Image dithering, Simplex noise, Static mesh gradient and Static
radial gradient are ports of
Paper's Image Dithering,
Simplex Noise,
Static Mesh Gradient and
Static Radial Gradient,
from the GLSL at the same commit
(image dithering,
simplex noise,
static mesh gradient,
static radial gradient),
under the same licence. Image dithering reduces the input image to a palette
with random or 2×2, 4×4 or 8×8 Bayer dithering; set original_colors to 1 to
keep the image's hues. The other three draw patterns and ignore the input image
except for its dimensions. All four output opaque colors, apart from image
dithering's original_colors mode, which keeps Paper's alpha. The defaults
follow Paper's default presets, with time at 0. We changed them to fit what the
compiler supported when they were ported:
- The Bayer matrices are built from the interleaved bits of
x ^ y and y,
in place of constant arrays. They give the same thresholds as Paper's tables.
- Image dithering fills the frame with the image, as Paper's
cover fit does
when the image and canvas match, samples it nearest-neighbour, and leaves out
the frame fade, which is always 1 here.
- Loops are unrolled: simplex noise has up to five colors, the static mesh
gradient up to four and the static radial gradient up to three, matching
their default presets in place of Paper's ten.
- Simplex noise and the static radial gradient emulate
fwidth like Fluted
glass, and keep their smoothstep edges and divisions apart where it is 0.
- Both static gradients leave out grain, and simplex noise leaves out the
color-banding dither, as Swirl does.
pow is kept defined at 0 by flooring or selecting around its base.
Liquid Metal (shapes) ports the built-in circle, daisy, diamond and
metaballs from Paper's Liquid Metal
(pinned GLSL source)
under the same licence. It draws a moving stripe pattern and uses the shape
edge to bend it. The input image supplies only the canvas size. Choose the
shape beside the control; adjust repetition, angle, contour, softness and
color dispersion to see how the edge changes the stripes.
This port covers Paper's built-in shapes, including its five-step metaball
loop. It omits uploaded-image masks, which Paper prepares with a Poisson
solver before the shader runs. The background is opaque, and a simple
procedural ripple replaces Paper's simplex noise and color-banding dither.
The shape edge and stripe antialiasing use fragment fwidth directly.
Color ring (vgpu) is the main.wgsl and color.wgsl example from the
vgpu home page, a glowing ring tinted by a cosine palette.
vgpu is © 2025 Vercel, Inc. and licensed under the
MIT License. The palette is inlined in place of
vgpu's WGSL import, and the size comes from the input texture in place of a
resolution uniform, so the input image supplies only the canvas size.
Colors are clamped to [0, 1], as vgpu's framebuffer does.
Fish eye, Stretch, Twirl, Squeeze and Light tunnel are
fragment shaders modelled on the distortions in macOS Photo Booth. They are
centred on the image, sample it bilinearly, and reflect positions outside it
back in.
- From Photo Booth's kernels: Photo Booth ships three Core Image kernels
as source in its app bundle. We rewrote their formulas in WGSL rather than
copying them. Fish eye reads from
0.6·d / (1 − d²/f²) along each ray, where
factor sets f in half-diagonals. At the default of 1.58 the corners stay
in place. Stretch is the fun-house kernel. It shifts pixels by a sine wave
that fades out by radius from the centre, and like the original, both
axes take their phase from p − center.y. All five shaders reflect
positions outside the image the way the mirror-edge kernel does.
- Like Core Image's filters: Twirl, Squeeze and Light tunnel follow
CITwirlDistortion, CIPinchDistortion and CICircleSplashDistortion,
which Photo Booth uses. Apple ships those kernels only as compiled Metal, so
our falloff curves are approximations.
Sizes are fractions of the image's shorter side.
Comic book (Photo Booth) follows Photo Booth's Comic Book effect. Photo
Booth builds it from three chains of Core Image filters, and the filter names
and settings are in its app binary:
- Colors:
CIHighlightShadowAdjust lifts the shadows, CIColorControls
raises saturation and contrast, and CIColorPosterize cuts each channel to
12 levels.
- Halftone:
CIColorMonochrome and CISpotColor turn luma into three
ink tones, and CIDotScreen prints them as dots 10 pixels apart at −23°.
Change dot_width to resize the dots.
- Ink:
CIUnsharpMask, CIColorControls and CISpotColor turn the
darkest areas and the dark side of edges black.
The colors show through the dots on white paper, multiplied by the ink overlaid
on the colors. Like Core Image, the shader mixes in linear light. Apple
doesn't publish how these filters work, so the shader approximates them,
checked against Core Image's output on a grey ramp and two photos:
CIHighlightShadowAdjust compares each pixel with its surroundings. The
shader uses one fixed shadow curve, measured on flat greys.
- The
CISpotColor tones and the CIColorControls brightness are measured
curves and fits, not Apple's formulas.
- The unsharp mask's blur is a 7×7 grid of samples 3 pixels apart.
- The dot pattern is a product of cosines, so dots sit in different places
from Core Image's.
On two stock macOS photos, pixels differ from Photo Booth's filters by about
3.5% on average, and our ink lines are slightly thinner.