GLSL Shader Examples
Common shader effects, each with the full code, a plain-language breakdown and a live preview you can edit. Copy them into your project, or keep tweaking them in the Playground.
Ray marching
Ray Marching an SDF Sphere
Trace one ray per pixel, advancing by the distance field. A hit epsilon and maximum distance terminate the loop.
Ray-Marched CSG Cutaway
A max with the negated sphere field carves the box. Estimate normals from the combined field.
Ray-Marched Tunnel with Repeating Arches
Fold z into a repeating cell containing an arch; camera translation moves the repeated structure past the viewer.
Visualizing SDF Normals in RGB
Centered differences estimate the gradient along three axes. Normalize and map it into RGB as a normal diagnostic.
Ray-Marched Soft Shadows
March from the hit point toward the light. The occluder distance divided by traveled distance approximates a penumbra; compare hard and soft halves.
Distance Fog in a Ray-Marched Scene
Hit distance drives exponential transmittance, mixing distant surfaces toward fog color rather than applying one flat screen overlay.
Triplanar Mapping on an SDF Rock
Blend three planar projections using normal-axis weights to avoid relying on one projection for steep rock faces.
Ray-Marched Torus
Measure distance to the torus major circle and subtract tube radius; inspect occlusion around the inner hole.
Ray-Marched Mandelbulb Fractal
Iterate a spherical power map and accumulate its derivative for a distance estimate. Iteration and ray steps are capped because this costs more than a sphere.
Ray-Marched Heightfield Terrain
A height function defines the surface. Reduce step size conservatively to mitigate tunneling; steep terrain still needs a tighter distance bound.
Images and post-processing
Sprite Outline from an Alpha Mask
Dilate alpha with a neighborhood maximum and subtract original alpha. This finds a silhouette, not brightness edges inside the leaf.
CRT Scanlines and Rolling Bright Band
Scanline density uses pixel coordinates while the rolling band uses normalized coordinates, keeping spatial frequency separate from speed.
Pixelation Shader with Square Cells
Quantize screen pixels before normalizing. The cells stay square in both portrait and landscape canvases.
Bayer Ordered Dithering
A fixed 4×4 threshold pattern turns gray into binary dots. Cell scale magnifies the pattern without changing source luminance.
Radial Chromatic Aberration
Sample red and blue in opposite radial directions while green stays fixed; displacement vanishes near the center.
3×3 Gaussian Blur Shader
The 3×3 kernel uses products of 1,2,1 weights summing to 16. The three columns show source, mean blur and Gaussian blur; the slider changes tap spacing.
Sobel Edge Detection Shader
Two Sobel kernels estimate horizontal and vertical luminance changes. Gradient magnitude is bright at edges and dark in flat regions.
Halftone Dot Shader
Luminance controls dot area, so radius uses a square-root mapping. Darker regions produce larger dots in equal-sized cells.
Digital Glitch with Horizontal Band Displacement
Hash strip index with discrete time so pixels in one band move together while unselected bands remain stable.
Ripple Refraction on an Image
The radial wave displaces sampling coordinates rather than being painted as color. Watch straight lines in the fixture bend.
Kaleidoscope UV Folding
Fold angle into one wedge and mirror it. Preserve radius so texture lookup reflects continuously across wedge axes.
Raindrop Refraction on Glass
Define a droplet inside each cell and use its local radial field to displace the background only near the droplet.
Heat Haze Distortion
Multiply horizontal distortion by a localized heat mask so the image away from the horizon stays stable.
Hexagonal Bokeh Blur
Accumulate and normalize samples inside a hexagonal aperture; bright dots on black expand into the aperture shape.
Localized Swirl Distortion
Rotation angle falls to zero with radius so the outer image remains fixed rather than rotating as a whole.
Glass Sphere Background Refraction
Compute a refracted direction from a sphere normal and use its lateral component to offset the background. This single-interface screen-space approximation omits internal bounces.
Two-Pass Separable Gaussian Blur
The first pass filters x; the second filters its output along y. Use the pass selector to inspect the horizontal intermediate.
Threshold Bloom with Blurred Highlights
Extract highlights, blur them, then add them to the original. These RGBA8 teaching targets demonstrate threshold and spread rather than an HDR bloom pipeline.
Depth-of-Field Blur from a Depth Texture
The depth fixture varies from left to right. Focus selects the sharp band; depth difference controls blur radius. This introductory gather filter does not solve foreground occlusion leakage.
Simulation and feedback
Feedback Trails with Ping-Pong Buffers
Each frame reads the previous trail, fades it, adds a new point, then swaps read/write targets. Pause freezes state; Reset clears history.
Interactive Heightfield Water Ripples
A two-time-level finite-difference wave simulation with click impulses. Two bytes per height reduce quantization drift on RGBA8 targets.
Gray–Scott Reaction-Diffusion Patterns
Two channels store A/B concentrations. Diffusion, reaction, feed and kill terms advance a Gray–Scott model. Parameters change the evolution; mature structures require many frames.
Dye Advection in a Velocity Field
Backtrace through a prescribed velocity field to sample previous color, then inject dye. This demonstrates advection without pressure projection or a full incompressible fluid solver.
Conway’s Game of Life on the GPU
Each texel is a cell. Count eight neighbors and apply B3/S23. A fixed repeating glider seed makes initialization reproducible; the boundary clamps instead of wrapping.
Shapes
Circle
Draw a crisp, anti-aliased circle with a signed distance function, length() and smoothstep().
Rounded Rectangle
A rounded rectangle SDF with fill and outline, the building block for buttons and UI cards in shaders.
Neon Glow
A glowing neon ring made by dividing a small number by the distance to a line.
Capsule SDF Between Two Points
Clamp the segment projection to its endpoints, measure distance to the closest point, then subtract the radius.
Five-Point Star SDF
A ten-edge star polygon with alternating inner and outer radii, minimum edge distance and a ray-crossing inside sign.
Circular Progress Arc with Rounded Caps
An angular threshold keeps part of the ring, while small circles cap the two endpoints without changing stroke width.
SDF Subtraction: A Circular Cutout
Subtraction uses max(a,-b): stay inside the box while excluding the circle.
Metaballs with a Smooth SDF Union
The left half uses a hard union and the right half a smooth union. Blend width changes the neck geometry rather than blurring final color.
Constant Pixel Width SDF Outline
The left uses a fixed distance threshold; the right estimates pixel width from screen derivatives. Change radius and compare the stroke widths.
Marching Ants Selection Border
Accumulate arc length along all four edges and use one perimeter coordinate so the dash phase continues through each corner.
Patterns
Checkerboard
A scrolling checkerboard pattern built from floor() and mod() in four lines of GLSL.
Rotating Tiles
Rotate coordinates with a 2D rotation matrix, then repeat a square across the screen with fract().
Hex Grid with Per-Cell Pulses
A staggered grid approximates honeycomb cells. Cell IDs drive independent pulses and both border and color share coordinates.
Truchet Tile Maze
Each tile selects one of two arc orientations with endpoints at edge midpoints, preserving connections after random flips.
Triangular Tessellation Pattern
Transform into an oblique lattice and split each cell along its diagonal to index the two triangles independently.
Moiré Interference Between Line Grids
Multiply two nearby high-frequency orientations to reveal a low-frequency beat. Fine lines can alias; reduce frequency to inspect.
Color
Noise
Random Numbers
GLSL has no random() function. Here is the one-line hash everyone uses, and how to turn it into random grid cells.
Value Noise
Smooth 2D noise in GLSL: random values on a grid, blended with smoothstep-style interpolation.
Clouds (fBm)
Drifting procedural clouds made by stacking octaves of noise with fractal Brownian motion (fBm).
Voronoi (Cellular Noise)
Animated Voronoi cells in GLSL: scatter one random point per grid cell and color each pixel by its distance to the nearest point.
Motion and effects
Water Ripple
Expanding water ripples from the center: a sine wave over distance, moving with time and fading with exp().
Fire
A procedural fire shader: rising fBm noise shaped into a flame and mapped to a black-red-yellow-white color ramp.
Noise Dissolve with a Burning Edge
One threshold keeps or removes a pixel; a second narrow interval adds the burning edge. Progress and edge width can be adjusted independently.
Glowing Voronoi Cracks
Use the difference between the nearest two cell distances as an edge approximation; only near-equality boundaries emit light.
Hologram Shader with a Moving Scan Band
Multiply a silhouette by high-frequency scanlines and add one slower scan band. Random displacement affects only selected horizontal strips.
Radar Sweep with Fading Blips
Compute time since the sweep from modular angular difference. Fixed-target afterglow can therefore be evaluated without a history buffer.
Hexagonal Energy Shield
Use the sphere normal for a bright Fresnel-like rim, then overlay a procedural honeycomb approximation and a moving pulse band. The grid is projected, not geometry.
Brushed Metal with Directional Highlights
Fine grain and the stretched highlight share one rotated coordinate system, so rotating the brush direction rotates both.
Three-Band Toon Shading
Calculate a continuous diffuse term, then quantize its intensity. Lighting bands move with the light because intensity, not screen position, is quantized.
Logarithmic Spiral Arms
Combine log radius with angle to create arms that tighten toward the center; clamp radius to avoid log zero.
Radial Anime Speed Lines
Narrow angular bands appear only near the perimeter. Discrete time controls flicker while a center mask leaves room for a subject.
Warp-Speed Star Trails
Angle fixes trail direction while reciprocal radius and time create radial motion. Trails stretch toward the perimeter.
Liquid Wipe Transition
Noise distorts only the mask between two procedural patterns. Clamp progress endpoints to ensure either input can be shown in full.
Layered Parallax Mountain Landscape
Move each mountain layer at a different speed and draw back-to-front, using lighter distant layers and darker foreground.
Procedural Aurora Curtains
A curved baseline, upward falloff and fine vertical strands form a 2D curtain. This is a screen-space approximation rather than volumetric scattering.
Procedural Water Caustics
Domain-warped cell edges produce moving pool-floor patterns. This procedural approximation does not solve light focusing.
Crosshatching Shader
Add more stroke orientations in progressively darker lighting bands. The shader varies line coverage rather than just painting gray bands.
Want to understand every line?
Every built-in function used here is explained in the function reference. To learn from scratch, start the learning path from lesson one.