Hacker News new | ask | show | jobs
by greggman 4349 days ago
Basically you draw a single quad (2 triangles) covering the entire screen using OpenGL (or DirectX).

A Pixel shader is run when rendering each pixel of the quad. It's only input is often `time` and `resolution`.

At least in GLSL there's a global variable, `gl_Fragcoord` and provides the integer position of the pixel currently being drawn. So for example the pixel at the bottom left is gl_Fragcoord = vec2(0,0). The one directly to the right of that is gl_Fragcoord = vec2(0,1)

Given you're also passed the resolution can get a value that goes from 0 to 1 over the screen with

   vec2 zeroToOne = gl_Fragcoord.xy / resolution;
If you were to dump that value directly do the screen you'd get a red gradient going black to red from left to right and a green gradient from black to green going from bottom to top. See http://glsl.heroku.com/e#18516.0

Now it's up to you to use more creative math that given just gl_Fragcoord, resolution, and time write a function that generates an image.

You can play with that in your browser here, http://glsl.heroku.com and here http://shadertoy.com

2 comments

Wouldn't it be even easier to draw one triangle that extends beyond the screen so that it covers it entirely and let the pipeline clip it to the screen size?
So the whole point of using a shader is that it's the GPU that's doing all the work?
Yes, that's what this trick is for.

In most standard 3D graphics, the CPU passes a description of the scene as polygons to the GPU, which then does two[1] shader steps - vertex and fragment[2] shading. The vertex shading works at the level of triangle vertices, effectively translating and and transforming the vertices, and then the fragment shader colors in each individual pixel.

So for a standard scene, the CPU tells the GPU: 'Right, we've got a room, with some pillars, and a monster, and a few lights, positioned like this', and then the CPU calculates what that looks like.

What Inigo is doing is that the CPU only knows there are two triangles - a quad covering the scene - so it just tells the GPU to draw a flat rectangle. The vertex shader does nothing but maintain the flat rectangle. However, because the fragment shader can be arbitrary logic, rather than just painting it with a solid color or even a texture, it is running its own simulation that involves drawing an entire scene.

----

[1] More these days with Geometry shaders, but that's another topic

[2] Sometimes called a pixel shader, although really that's incorrect - Fragment is a more accurate term