FragmentShader
A canvas, a full-screen triangle, a render loop and two uniforms, ready for a fragment shader.
FragmentShader is the quickest way to put a shader on a page. It makes a Renderer and appends its canvas, covers the canvas with a Triangle, makes a Program from your shaders, and starts a requestAnimationFrame loop that keeps u_time and u_resolution up to date. Your first shader is the short version; this page covers every option.
import { FragmentShader, Vec2 } from 'wtc-gl'
// A full-screen fragment shader: FragmentShader makes the renderer, a
// triangle that covers the canvas and the render loop, and keeps u_time and
// u_resolution up to date.
const vertex = /* glsl */ `#version 300 es
in vec3 position;
in vec2 uv;
out vec2 v_uv;
void main() {
v_uv = uv;
gl_Position = vec4(position, 1.0);
}`
const fragment = /* glsl */ `#version 300 es
precision highp float;
uniform vec2 u_resolution;
uniform float u_time;
in vec2 v_uv;
out vec4 colour;
void main() {
// Centred, aspect-correct coordinates
vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;
float t = u_time * 20.0;
float rings = sin(length(p) * 24.0 - t * 3.0);
vec3 a = vec3(0.29, 0.62, 1.0);
vec3 b = vec3(0.95, 0.42, 0.26);
colour = vec4(mix(a, b, smoothstep(-0.3, 0.3, rings + p.x)), 1.0);
}`
export default function (container) {
const shader = new FragmentShader({
vertex,
fragment,
container,
// Sized to the container below, rather than the window
autoResize: false
})
// The page drives the frames, so it can pause off screen
shader.playing = false
return {
frame(time) {
shader.render(time * 1000)
},
resize(width, height) {
shader.dimensions = new Vec2(width, height)
shader.renderer.dimensions = shader.dimensions
shader.u_resolution.value = shader.dimensions.scaleNew(
shader.renderer.dpr
).array
},
dispose() {
shader.destroy()
}
}
}Options
Everything is optional. With no options at all you get a demo gradient filling the window.
import { FragmentShader, Uniform, Vec2 } from 'wtc-gl'
const shader = new FragmentShader({
vertex, // default: passes the triangle through, with a v_uv varying
fragment, // default: a demo colour gradient
container: document.querySelector('.hero'), // default: document.body
autoResize: false, // default: true, follow the window
dimensions: new Vec2(800, 450), // CSS pixels, used when autoResize is off
uniforms: { u_pointer: pointer }, // added to u_time and u_resolution
rendererProps: { dpr: 2, alpha: true }, // passed to the Renderer
onInit(renderer) {}, // once, after the renderer is made
onBeforeRender(time) {}, // each frame, before drawing
onAfterRender(time) {} // each frame, after drawing
})vertexandfragmentare the shader sources. The default vertex shader is GLSL 1.00, withattribute vec3 position,attribute vec2 uvand avarying vec2 v_uv. A GLSL 3.00 fragment shader needs a GLSL 3.00 vertex shader to match, like the one in the example above.containeris the element the canvas is appended to. Passnullto leave the canvas out of the page, and appendshader.gl.canvasyourself.autoResize(defaulttrue) sizes the canvas to the window and listens for the window'sresizeevent. Turn it off to size the canvas todimensionsinstead, which defaults to the window size when the shader is made.uniformsare added to the program alongsideu_timeandu_resolution. The keys are the names in the shader. Au_timeoru_resolutionof your own is replaced by the recipe's.rendererPropsare RendererOptions for the renderer. The recipe setsclearColourto opaque white unless you pass one. Passcanvasto draw into a canvas you already have.onInitis called with the renderer once it's made, before the program, the triangle and the first frame. Use it for renderer state the program depends on, such as an extension.onBeforeRenderandonAfterRenderare called every frame, with therequestAnimationFrametimestamp in milliseconds,time. It's the timestamp, not the time since the last frame. They're bound to the shader, so afunction(not an arrow) can usethis.
See FragmentShaderOptions for the types.
u_time and u_resolution
Every frame the recipe adds the time since the last frame, in milliseconds and capped at 50, multiplied by 0.00005, to u_time. At 60 frames a second that's about 0.05 a second, so u_time reaches 1 after 20 seconds. Shaders usually scale it up (u_time * 20.0 is roughly seconds). The cap means a frame after a long pause, such as when the tab was in the background, moves time on by no more than 0.0025.
u_resolution is the canvas size in device pixels: the CSS size times the renderer's dpr. It's the same space as gl_FragCoord, so gl_FragCoord.xy / u_resolution runs from 0 to 1 across the canvas.
Both are Uniforms on the shader, shader.u_time and shader.u_resolution, and their values can be set: shader.u_time.value = 0 starts time again.
precision highp float;
uniform vec2 u_resolution;
uniform float u_time;
void main() {
vec2 uv = gl_FragCoord.xy / u_resolution;
gl_FragColor = vec4(uv, 0.5 + 0.5 * sin(u_time * 40.0), 1.0);
}Sizing the canvas yourself
With autoResize on, shader.resize() sizes the canvas to the window and updates u_resolution. It always reads the window, so with autoResize off, resize the canvas and the uniform yourself, for instance from a ResizeObserver on the container:
import { FragmentShader, Vec2 } from 'wtc-gl'
const container = document.querySelector('.hero')
const shader = new FragmentShader({ fragment, container, autoResize: false })
new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect
shader.dimensions = new Vec2(width, height)
shader.renderer.dimensions = shader.dimensions
shader.u_resolution.value = shader.dimensions.scaleNew(
shader.renderer.dpr
).array
}).observe(container)The renderer only sets the canvas's drawing buffer, width and height in device pixels. Its size on the page is up to your CSS, in either mode. Without any, a canvas with a dpr of 2 shows at twice its CSS size:
.hero canvas {
display: block;
width: 100%;
height: 100%;
}For a full-window shader, position: fixed; inset: 0 does the same job.
Playing and stopping
playing starts and stops the loop. Stopping cancels the frame that was already requested and restarts the frame clock, so the frame after playing = true adds no time, however long the shader was stopped. u_time keeps its value.
shader.playing = false // pause
shader.playing = true // carry on from the same u_timeresetTime() restarts the frame clock without stopping, so the next frame adds no time. It doesn't set u_time back to 0.
To drive the frames yourself, from a scroll position or another loop, stop it and call render with a timestamp in milliseconds. The live example above does this, so the page can pause it while it's off screen:
shader.playing = false
function frame(t) {
shader.render(t)
requestAnimationFrame(frame)
}
requestAnimationFrame(frame)Don't call render while playing is on: it requests the next frame itself, so each call would start another loop.
Feedback with post
Set post to a Framebuffer, and the recipe draws each frame into it instead of the canvas, then swaps its two targets. The shader can read post.read.texture, the frame before, which is how you make trails, smears, reaction-diffusion and other effects that build on themselves.
Nothing reaches the canvas until you draw it there. onAfterRender is the place: by then post.read holds the frame that was just drawn.
import {
FragmentShader,
Framebuffer,
Mesh,
Program,
Uniform,
Vec2
} from 'wtc-gl'
// Feedback with `post`: the shader draws into a Framebuffer instead of the
// canvas, reading its own last frame, and onAfterRender shows the result.
const vertex = /* glsl */ `#version 300 es
in vec3 position;
in vec2 uv;
out vec2 v_uv;
void main() {
v_uv = uv;
gl_Position = vec4(position, 1.0);
}`
const fragment = /* glsl */ `#version 300 es
precision highp float;
uniform vec2 u_resolution;
uniform float u_time;
uniform sampler2D u_previous;
in vec2 v_uv;
out vec4 colour;
void main() {
vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;
float t = u_time * 60.0;
vec2 head = vec2(0.6 * sin(t * 1.1), 0.32 * sin(t * 1.7));
float spot = smoothstep(0.045, 0.03, distance(p, head));
vec3 tint = 0.5 + 0.5 * cos(t * 0.5 + vec3(0.0, 2.0, 4.0));
// Last frame, drawn slightly larger so the trail drifts outwards, and faded
vec4 last = texture(u_previous, 0.5 + (v_uv - 0.5) * 0.996);
last = max(last * 0.985 - 0.002, 0.0);
colour = mix(last, vec4(tint, 1.0), spot);
}`
const show = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D u_result;
in vec2 v_uv;
out vec4 colour;
void main() {
colour = texture(u_result, v_uv);
}`
export default function (container) {
const u_previous = new Uniform({
name: 'previous',
value: null,
kind: 'texture'
})
const u_result = new Uniform({ name: 'result', value: null, kind: 'texture' })
let display
const shader = new FragmentShader({
vertex,
fragment,
container,
autoResize: false,
uniforms: { u_previous },
rendererProps: {
dpr: Math.min(devicePixelRatio, 2),
alpha: true,
premultipliedAlpha: true,
clearColour: [0, 0, 0, 0]
},
// Read the last frame while the shader draws into the other target
onBeforeRender() {
u_previous.value = shader.post.read.texture
},
// Draw the frame that was just made onto the canvas
onAfterRender() {
u_result.value = shader.post.read.texture
shader.renderer.render({ scene: display })
}
})
shader.playing = false
const { gl } = shader
shader.post = new Framebuffer(gl, { dpr: shader.renderer.dpr, depth: false })
display = new Mesh(gl, {
geometry: shader.mesh.geometry,
program: new Program(gl, { vertex, fragment: show, uniforms: { u_result } })
})
return {
frame(time) {
shader.render(time * 1000)
},
resize(width, height) {
shader.dimensions = new Vec2(width, height)
shader.renderer.dimensions = shader.dimensions
shader.u_resolution.value = shader.dimensions.scaleNew(
shader.renderer.dpr
).array
shader.post.resize(width, height)
},
dispose() {
display.program.remove()
shader.post.remove()
shader.destroy()
}
}
}The steps are:
- Add a texture uniform for the last frame, and set it to
shader.post.read.textureinonBeforeRender. The targets swap on every render, so set it every frame. - Make a
Framebufferthe size of the canvas: the same CSS size and the renderer'sdpr. Turndepthoff, since a full-screen pass doesn't need one. Resize it with the canvas. - In
onAfterRender, draw a second mesh that showsshader.post.read.texturewithshader.renderer.render. It can share the recipe's triangle,shader.mesh.geometry.
The framebuffer's textures are 8-bit by default. A fade that multiplies the last frame by a number just under 1 gets stuck at faint values, since each step rounds back up; subtracting a little too, as the example does, makes sure it reaches 0. For more precision, pass texdepth: Framebuffer.TEXTYPE_HALF_FLOAT. The ping-pong cookbook goes further, with a simulation step and a separate display pass.
Set post back to null to draw to the canvas again.
Cleaning up
destroy() stops the loop, removes the window resize listener, and deletes the triangle and the program. If the renderer made the canvas, it's removed from the page and its WebGL context is released. A canvas you passed as rendererProps.canvas stays where it is. destroy() returns the canvas either way.
shader.post?.remove() // a post framebuffer is yours to remove
shader.destroy()Programs, textures and framebuffers you made yourself, post among them, aren't touched. Remove them before calling destroy(), while the context is still alive. See Cleaning up.
Related
- Your first shader
- Programs and shaders and Uniforms
- Render targets, for
Framebuffer - Pointer uniforms, for passing the pointer into a shader
- The fragment shader demo
- API: FragmentShader, FragmentShaderOptions, Framebuffer