This example uses the vertex shader to move the actual position of vertices rather than just their color. It also shows how to draw a plane using triangle strips in Processing. Thanks to Andres Colubri for help debugging!
Code here: https://github.com/atduskgreg/Processing-Shader-Examples/tree/master/vertex_shader_ripple_plane. And reproduced in full after the notes.
When running it looks like this:
This shader moves the points on a plane up and down based on the position of the mouse. It calculates the Z position of each point as a kind of sine wave of the point’s position on the plane (multiplying by the mouseX position which is passed in as a uniform variable to make it interactive):
thisPos.z += mouseX * sin(thisX*thisX + thisY*thisY);
Since this changes the angle of the vertex relative to the light source, we have to recalculate the vertex’s normals so that lighting will still work on it correctly:
thisNorml.x = 2. * 0.3 * thisX * cos(thisX*thisX + thisY*thisY); thisNorml.y = 2. * 0.3 * thisY * cos(thisX*thisX + thisY*thisY); thisNorml.z = 1.;
In looking at this shader, Andrew suggested something I could do to make it more efficient. Instead of constantly accessing the x- and y-coordinates of the current vertex as separate variables, I could use a technique he called "coordinate sizzling" to access multiple of them at once.
Instead of doing something like this (what I currently do):
float thisX = thisPos.x; float thisY = thisPos.y; thisPos.z += mouseX * sin(thisX*thisX + thisY*thisY);
I could do this:
thisPos.z += 20.0 * sin(dot(thisPos.xy, thisPos.xy)
This second version accesses both the x- and y-coordinates simultaneously. Apparently, it’s more efficient.
In introducing this shader example, Bailey and Cunningham say that they applied it to a quad defined "from -5 to 5 with 20 subdivisions". This was rather vague so I experimented a bit with Processing’s geometry options. Just drawing a simple four-vertex quad with "beginShape(QUADS)" didn’t work, the shader had no visible effect. So I tried again, this time with a TRIANGLE_STRIP. When I did that the shader started taking effect. Since it’s a vertex shader, it only operates on vertices, I guess, and so needed more vertices to manipulate. The distortion still seems a big, er, pointy, though so I think I’m not quite doing something right still. The illustration in the book had a nice ripples in water quality to it.