GLSLCanvas From “Scratch”
If you wish to make an apple pie from scratch, you must first invent the universe.
― Carl Sagan, Cosmos
Last week we looked at fragment shader programming using the very handy glslEditor. glslEditor sets up a WebGL context to run your fullscreen fragment shader in. It provides some basic context information through the uniforms u_resolution, u_mouse, and u_time.
By the end, we should have something like this:
I like to start every program with a minimal hello world. Hopefully just a few lines of code to get something on the screen and make sure everything is working correctly. That way, if something does go wrong, I only have to look through a few lines of code to find the problem.
Even a pretty minimal WebGL program has several parts. It needs to create a context, load and compile both a vertex shader and fragment shader, buffer the geometry to draw, and then actually draw it.
This comes out to a full screen of code across three seperate programs written in two languages. If something does go wrong, there is a lot to check.
- Partner up!
- Open the Scrimba link below and read the code together. Think about what the code might be doing. Don’t look anything up.
- I’ve removed the comments. Recomment this code by placing the comments at the bottom of the page where they belong.
- Write down any and all questions you have.
Adding a Varying Attribute
A vertex shader can calculate data to provide to the fragment shader. Each fragment will recieve an interpolated value based on its position relative to the surrounding vertecies. Because there are typically far more fragments than vertecies, moving complex calculations to the vertex shader can improve performance at some cost to accuracy.
Next we’ll add vertex color data that will be interpolated and passed to the fragment shader.
Adding Uniform Attributes
Sometimes the fragment or vertex shader need access to data from the host program. The host program can pass in this data a uniform attributes. Uniforms have the same value for every vertex and fragment, but they can change between draw calls and animation frames.
Next we’ll add uniforms for the mouse position and time.
gl_FragCoord vs UVs
The shader currently is using the gl_FragCoord. Lets look at what happens when we move the geometry around the screen and compare that to providing a varying uv attribute.